Explain Codes LogoExplain Codes Logo

Create an empty list with certain size in Python

python
list-comprehensions
performance
best-practices
Anton ShumikhinbyAnton Shumikhin·Feb 3, 2025
TLDR

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:

empty_list = [None] * 10 # We've got space for 10, who's in?

Mutable Example:

empty_list = [[] for _ in range(10)] # Ten little ships in our mighty fleet!

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.

xs = [] for value in range(10): xs.append(value) # xs is growing... it's alive!

Quick integer lists

Need a list of integers quickly? Call in our old friend range().

integers = list(range(10)) # Counting like a toddler, but fast like a ninja

Complex list comprehensions

If you need a list with complex expressions, list comprehensions are here for you:

squares = [x**2 for x in range(9)] # squaring away the numbers!

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:

two_d_list = [[None] * cols for _ in range(rows)] # 2D chess anyone?

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:

matrix = [[] for _ in range(size)] # Each sublist is unique, like you and me!

Wise use of list comprehensions

Use them when they enhance clarity and performance:

even_numbers = [x for x in range(20) if x % 2 == 0] # The odd ones are out!

Generator expressions for memory management

For large data sets, consider generator expressions. They save memory while giving the same output as list comprehensions:

lazy_squares = (x**2 for x in range(10**6)) # Millionaire lazy squares