Is it possible to specify the size of list at construction?

Steven Bethard steven.bethard at gmail.com
Tue Mar 1 15:51:44 EST 2005


Michael Spencer wrote:
> Anthony Liu wrote:
> 
>> I cannot figure out how to specify a list of a
>> particular size.
>>
>> For example, I want to construct a list of size 10,
>> how do I do this?
>>
> A list does not have a fixed size (as you probably know)
> 
> But you can initialize it with 10 somethings
>  >
>  >>> [None]*10
>  [None, None, None, None, None, None, None, None, None, None]
>  >>> range(10)
>  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>  >>>

Also, list comprehensions may be useful if you have mutable objects:

[{} for _ in range(10)]

And to see why [{}]*10 is probably not what you want:

py> lst = [{}]*10
py> lst[0][1] = 2
py> lst
[{1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, 
{1: 2}]
py> lst = [{} for _ in range(10)]
py> lst[0][1] = 2
py> lst
[{1: 2}, {}, {}, {}, {}, {}, {}, {}, {}, {}]

STeVe



More information about the Python-list mailing list