David Y.
—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?
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)
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].
If you are a California resident, see our Supplemental notice.