List Syntax#
Note
Source: Adapted from the C# edition (arrays/onedim.rst and
lists/listsyntax.rst). Python lists replace both C# fixed-size
arrays and List<T>. Python lists are mutable, dynamically sized,
and can hold elements of mixed types.
A list is an ordered, mutable sequence of values. It is the most commonly used collection in Python.
Creating Lists#
Use square brackets to write a list literal:
nums = [4, 7, -2, 5]
words = ["up", "down", "over"]
empty = []
mixed = [1, "hello", 3.14] # mixed types are allowed
list() converts any iterable to a list:
chars = list("abc")
print(chars)
Output:
['a', 'b', 'c']
Indexing and Length#
Elements are accessed by integer index starting at 0:
nums = [4, 7, -2, 5]
print(nums[0]) # first element
print(nums[3]) # last element
print(len(nums)) # number of elements
Output:
4
5
4
Negative indices count from the end: nums[-1] is the last element,
nums[-2] is the second-to-last, and so on.
Mutation#
Unlike strings, lists can be changed after creation:
nums = [4, 7, -2, 5]
nums[2] = 99
print(nums)
Output:
[4, 7, 99, 5]
Slicing#
A slice extracts a sub-list. The syntax is lst[start:stop], which
returns elements from index start up to (but not including) stop:
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # indices 1, 2, 3
print(nums[:3]) # from the beginning through index 2
print(nums[2:]) # from index 2 to the end
print(nums[:]) # a copy of the whole list
Output:
[20, 30, 40]
[10, 20, 30]
[30, 40, 50]
[10, 20, 30, 40, 50]
A slice always produces a new list; the original is unchanged.
Membership Test#
The in operator tests whether a value is anywhere in the list:
words = ["up", "down", "over"]
print("down" in words)
print("around" in words)
Output:
True
False
Iterating Over a List#
Use a for loop to visit each element:
for word in ["cat", "dog", "bird"]:
print(word.upper())
Output:
CAT
DOG
BIRD
To iterate with an index, use enumerate():
scores = [88, 73, 95]
for i, score in enumerate(scores):
print(f"{i}: {score}")
Output:
0: 88
1: 73
2: 95