Create an empty list with certain size in Python
To create an empty list with a specific size, you can use [None] * size
for immutable elements, or [[] for _ in range(size)]
for independent mutable ones.
Immutable Example:
Mutable Example:
Be wary when initializing mutable containers, it's crucial to create independent inner lists or unforeseen changes will propogate throughout due to reference duplication.
Techniques for different scenarios
In Python, several techniques allow you to create and manipulate lists. The choice of method depends on your particular requirements.
Dynamically growing lists
If you need to grow a list incrementally, the append()
method comes to the rescue.
Quick integer lists
Need a list of integers quickly? Call in our old friend range()
.
Complex list comprehensions
If you need a list with complex expressions, list comprehensions are here for you:
Avoiding shared references
When obj
is mutable, [obj] * n
creates a list of n
references to the same obj
. For distinct mutable objects always use a list comprehension.
Independent mutable lists
Creating a 2D list or list of lists? Make sure each sublist is independently mutable:
Error-proofing list additions
An "IndexError: list assignment index out of range" occurs when trying to assign to a non-existent index. The .append()
method sidesteps this issue beautifully.
Performance considerations
For speed demons, [None] * x
is generally faster than [None for _ in xrange(x)]
.
Tips for robust list usage
To master list manipulations, these tips would come handy:
Reference traps in nested lists
For initializing a 2D list, ensure independent sublists to avoid reference issues:
Wise use of list comprehensions
Use them when they enhance clarity and performance:
Generator expressions for memory management
For large data sets, consider generator expressions. They save memory while giving the same output as list comprehensions:
Was this article helpful?