Create a list of a given size in Python

David Y.

The Problem

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:

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

It fails with the following error:

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:

numbers = list(range(0, 10))

Additional examples of list creation code are:

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:

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):

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:

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:

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.

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.

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:

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.

max10.pop() max10.popleft() print(max10) # will print deque([1, 2, 3, 4, 5, 6, 7, 8], maxlen=10)

Get Started With Sentry

Get actionable, code-level insights to resolve Python performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a Python project and note your DSN

  3. Grab the Sentry Python SDK

pip install --upgrade sentry-sdk
  1. Configure your DSN
import sentry_sdk sentry_sdk.init( "https://<key>@sentry.io/<project>", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, )

Loved by over 4 million developers and more than 90,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.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

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