python中如何创建一个空列表,在python中创建具有特定大小的空列表

I want to create an empty list (or whatever is the best way) that can hold 10 elements.

After that I want to assign values in that list, for example this is supposed to display 0 to 9:

s1 = list();

for i in range(0,9):

s1[i] = i

print s1

But when I run this code, it generates an error or in another case it just displays [] (empty).

Can someone explain why?

解决方案

You cannot assign to a list like lst[i] = something, unless the list already is initialized with at least i+1 elements. You need to use append to add elements to the end of the list. lst.append(something).

(You could use the assignment notation if you were using a dictionary).

Creating an empty list:

>>> l = [None] * 10

>>> l

[None, None, None, None, None, None, None, None, None, None]

Assigning a value to an existing element of the above list:

>>> l[1] = 5

>>> l

[None, 5, None, None, None, None, None, None, None, None]

Keep in mind that something like l[15] = 5 would still fail, as our list has only 10 elements.

range(x) creates a list from [0, 1, 2, ... x-1]

# 2.X only. Use list(range(10)) in 3.X.

>>> l = range(10)

>>> l

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a function to create a list:

>>> def display():

... s1 = []

... for i in range(9): # This is just to tell you how to create a list.

... s1.append(i)

... return s1

...

>>> print display()

[0, 1, 2, 3, 4, 5, 6, 7, 8]

List comprehension (Using the squares because for range you don't need to do all this, you can just return range(0,9) ):

>>> def display():

... return [x**2 for x in range(9)]

...

>>> print display()

[0, 1, 4, 9, 16, 25, 36, 49, 64]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值