Sentry Answers>Python>

Create a list of a given size in Python

Create a list of a given size in Python

David Y.

The ProblemJump To Solution

In Python, how do I create a list of specific sizes and assign elements to it? I’ve tried using this code to create a list of length 10:

Click to Copy
numbers = list() for i in range(0, 10): numbers[i] = i

It fails with the following error:

Click to Copy
IndexError: list assignment out of range

Why does this happen and how do I fix it?

The Solution

In Python, lists do not have fixed sizes, and subscript notation (list[i]) can only be used to access and assign existing elements. This code creates an empty list (size 0) and then attempts to access positions 0 to 9, which do not exist.

A more Pythonic way to create the list in the code above would be to use the range function directly in the list creation:

Click to Copy
numbers = list(range(0, 10))

Additional examples of list creation code are:

Click to Copy
empty_list = list() # list with zero elements other_empty_list = [] # list with zero elements, alternate syntax short_list = ["Hello world!"] longer_list = [1, 2, 3]

Because lists do not have fixed sizes, elements can be added to the end of any existing list using the list.append method:

Click to Copy
empty_list.append(1) # will now be [1] short_list.append("It's me!") # will now be ["Hello world!", "It's me!"] longer_list.append(4) # will now be [1, 2, 3, 4]

Elements can also be removed using the list.pop method (without a position argument, the last element in the list will be removed):

Click to Copy
empty_list.pop() # will now be [] short_list.pop() # will now be ["Hello world!"] longer_list.pop(0) # will now be [2, 3, 4], as the element at index 0 was removed

Additional methods for adding and removing items from lists are detailed here. Note that adding and removing items in this way will change the length of the list. Additionally, when items are added or removed at arbitrary positions, this will affect the indices of other items in the list.

If a list containing a certain number of blank or dummy elements is needed, we can create one as follows:

Click to Copy
blank_list = [None] * 10 # will produce [None, None, None, None, None, None, None, None, None, None]

None is a special Python object used to indicate null values. Because this list contains values at indices 0 to 9, we can access and reassign them. Therefore, we could use this method with the original code without producing an IndexError:

Click to Copy
numbers = [None] * 10 for i in range(0, 10): numbers[i] = i

Note that this list can still be added to and removed from. To create a fixed-width sequence with unchangeable elements, we should use a tuple instead of a list.

Click to Copy
my_tuple = tuple(range(0,10)) # will produce (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) print(my_tuple[0]) # will print 0 my_tuple[0] = 1 # will fail with "TypeError: 'tuple' object does not support item assignment" my_tuple.append(10) # will fail with "AttributeError: 'tuple' object has no attribute 'append'" my_tuple.pop() # will fail with "AttributeError: 'tuple' object has no attribute 'pop'"

If a tuple is too restrictive and we just want to be able to change individual elements while keeping the sequence to maximum length, we can use a deque from Python’s built-in collections module. This data structure supports an optional maximum length, specified on creation.

Click to Copy
from collections import deque max10 = deque([None] * 10, maxlen=10) print(max10) # will print deque([None, None, None, None, None, None, None, None, None, None], maxlen=10) for i in range(0, 10): max10[i] = i print(max10) # will print deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)

A deque is a double-end queue and has methods for appending to and popping from either side (append, appendleft, pop, popleft). Note that if an element is appended to a deque already at its maximum length, the element on the other side of the deque will be popped. For example:

Click to Copy
max10.append(10) print(max10) # will print deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxlen=10) max10.appendleft(-1) print(max10) # will print deque([-1, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)

Deques can also be smaller than their maximum length.

Click to Copy
max10.pop() max10.popleft() print(max10) # will print deque([1, 2, 3, 4, 5, 6, 7, 8], maxlen=10)
  • Sentry BlogPython Performance Testing: A Comprehensive Guide
  • Sentry BlogLogging in Python: A Developer’s Guide
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.