Creating and reading a list
marks = [78, 85, 90, 62]
print(marks[0]) # First item
print(marks[-1]) # Last item
print(marks[1:3]) # A slice
print(len(marks)) # How many
print(sum(marks)) # Total
print(max(marks), min(marks))Output
78 62 [85, 90] 4 315 90 62
Changing a list
fruits = ["apple", "mango"]
fruits.append("banana") # Add to the end
fruits.insert(0, "kiwi") # Add at a position
print(fruits)
fruits[1] = "orange" # Replace
fruits.remove("mango") # Remove by value
last = fruits.pop() # Remove and hand back the last item
print(fruits, last)
numbers = [3, 1, 2]
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)Output
['kiwi', 'apple', 'mango', 'banana'] ['kiwi', 'orange'] banana [1, 2, 3] [3, 2, 1]
The copying trap
a = [1, 2, 3]
b = a # NOT a copy: two names for one list
b.append(4)
print(a) # a changed too!
c = a.copy() # A real copy
c.append(5)
print(a)
print(c)Output
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5]
List comprehensions: a loop in one line
marks = [78, 35, 90, 22]
# The long way
doubled = []
for m in marks:
doubled.append(m * 2)
print(doubled)
# The short way
print([m * 2 for m in marks])
# With a filter
print([m for m in marks if m >= 40])Output
[156, 70, 180, 44] [156, 70, 180, 44] [78, 90]
Code challenge
Find the average of [10, 20, 30, 40].
sum(nums) / len(nums) gives 25.0.
Remove duplicates from [1, 1, 2, 3, 3].
list(set(nums)) works, though a set doesn't promise any order. The next page explains sets.
Finished reading?