Lists
A list is an ordered collection that you can change. Lists are the workhorse of Python: if you have several related values, they probably belong in a list.
Creating a list
fruits = ["apple", "banana", "cherry"]
numbers = [3, 1, 4, 1, 5]
mixed = [1, "two", 3.0, True]
empty = []
print(fruits, numbers, mixed, empty)Lists keep their order, allow duplicates and can hold any mix of types. list() also builds a list from any iterable:
print(list("hello"))
print(list(range(5)))Length
fruits = ["apple", "banana", "cherry"]
print(len(fruits))Indexing
Positions start at 0. Negative positions count from the end.
fruits = ["apple", "banana", "cherry", "mango"]
print(fruits[0])
print(fruits[-1])
print(fruits[1:3]) # slice: index 1 up to (not including) 3
print(fruits[:2])
print(fruits[2:])Asking for an index that does not exist raises IndexError.
Changing items
Unlike strings, lists are mutable.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)
fruits[0:2] = ["kiwi", "lime"] # replace a slice
print(fruits)Adding items
fruits = ["apple", "banana"]
fruits.append("cherry") # add to the end
fruits.insert(1, "avocado") # insert at index 1
fruits.extend(["mango", "fig"]) # add several
print(fruits)append(x) adds one item; extend(iterable) adds each item of the iterable. Mixing them up is a common bug:
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4]Removing items
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana") # first matching value
print(fruits)
last = fruits.pop() # remove and return the last item
print(last, fruits)
first = fruits.pop(0) # remove by index
print(first, fruits)
del fruits[0] # delete by index without returning
print(fruits)
fruits.clear()
print(fruits)Checking membership
fruits = ["apple", "banana"]
print("apple" in fruits)
print("mango" in fruits)Looping
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for i, fruit in enumerate(fruits):
print(i, fruit)Other useful operations
nums = [3, 1, 4, 1, 5, 9, 2]
print(nums.index(4)) # position of first 4
print(nums.count(1))
print(min(nums), max(nums), sum(nums))
print([1, 2] + [3, 4]) # concatenation
print([0] * 5) # repetitionPractice
- Make a list of five cities. Replace the third one, append a sixth, then print the list and its length.
- Remove the first and last items of
[10, 20, 30, 40, 50]usingpop()and print what remains. - Given
marks = [72, 85, 61, 94], print the average usingsum()andlen().
