How to have best use of Python lists?

Viewed 64

My question is te following: I'm new to Python programming and I'm a little confused about the correct use of lists. When I want for example to create a list of 10 elements I am doing something like:

list = [None for x in range(10)]

And when I have something to put on it, I do:

list[lastPosition] = data

But after some research I noticed that this use for lists is not efficient or recommended. But how other way could a list be inicialized before I have all the data? My idea is to have a list (specially something like Java's Collections) inicialized and as the data comes I fill it. I hope my question is clear enough.

1 Answers

If you don't know in advance how many elements will be in the list, then don't try to allocate 10 elements. Start with an empty list and use the append function to append to it:

lst = []
...
lst.append(value)

If for some reason you really need to initialize a list to a constant size, and the initial elements are immutable values, then you can do that like this:

lst = [None] * 10

If the initial elements are mutable values, you most probably don't want to use this technique, because all the elements will all point to the same instance. In that case your original technique is mostly fine as it was:

lst = [SomeClass() for _ in range(10)]

Note that I renamed the variable from list to lst, because list is a built-in class in Python, and it's better to avoid such overlaps.

Related