Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialise a list to a specific length in Python [duplicate]

Tags:

python

list

People also ask

How do I make a list a specific length in Python?

To create a list of n placeholder elements, multiply the list of a single placeholder element with n . For example, use [None] * 5 to create a list [None, None, None, None, None] with five elements None . You can then overwrite some elements with index assignments.

How do I make a list repeated values in Python?

We can use the append() method, the extend() method, or the * operator to repeat elements of a list in python.

How do you change the length of a list in Python?

To resize a list, we can use slice syntax. Or we can invoke append() to expand the list's element count. Notes on resizing. In addition to resizing, we can clear a list by assigning an empty list.

How do you initialize a list in Python?

To initialize a list in Python assign one with square brackets, initialize with the list() function, create an empty list with multiplication, or use a list comprehension. The most common way to declare a list in Python is to use square brackets.


If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.


list multiplication works.

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n to pre-allocate the length you want.

Slides available as PPT or via Google

The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.