list
in the
Python Glossary
array.array
is like a list of numbers that are all of the same type.
array.array
in the
Python Standard Library.
array.array
in
Tools
for working with lists
A list is an example of a (mutable) sequence.
A sequence is also an example of an iterable.
__iter__
method or a
__getitem__
method.
If we had thousands of numbers, we would have to invent thousands of names.
A year has 12 months. The first month has 31 days. The second month has 28 days. The third month has 28 days. The last month month has 31 days. The next-to-last month month has 30 days. The third-to-last month month has 31 days.
We have just mass-produced 12 variables,
named
months[0]
,
months[1]
,
months[2]
,
months[3]
,
…,
months[9]
,
months[10]
,
months[11]
.
These variables are called the
items
contained by the
list.
The integer in the
[
square brackets]
is called the
index
or
subscript.
Indexing a
list
is just like indexing a
str
ing.
The variable
months[0]
contains the int 31.
The variable
months[1]
contains the int 28.
The variable
months[2]
contains the int 31.
The variable
months[11]
contains the int 31.
Warning: there is no variable
months[12]
.
That’s because the indices of a list start at 0,
just like the indices of a
str
ing,
and in this example there are only 12 variables.
A year has 12 months. The first month has 31 days. The second month has 28 days. The third month has 31 days. The twelfth month has 31 days. The last month has 31 days. The next-to-last month has 30 days. The third-to-last month has 31 days.
months[12]
?
print(f"The thirteenth month has {months[12]} days.")
Traceback (most recent call last): File "/Users/myname/python/list2.py", line 31, in <module> print("The thirteenth month has", months[12], "days.") IndexError: index out of range
print(f"The third and a halfth month has {months[2.5]} days.")
Traceback (most recent call last): File "/Users/myname/python/Untitled.py", line 31, in <module> print("The third and a halfth month has", months[2.5], "days.") TypeError: list indices must be integers or slices, not float
str
ing
is an
immutable
sequence.
A
list
,
however,
is a
mutable
sequence.
months[1] = 29 #February print(f"The second month has {months[1]} days.")
The second month has 29 days.This gives us a way to change the characters of a string.
s = "counterclockwise" listOfCharacters = list(s) #Convert the string of chars into a list of chars. listOfCharacters[12] = "W" #A list, unlike a string, is mutable. s = "".join(listOfCharacters) #Convert the list back into a string. print(s)
counterclockWise