Python Lists
A list stores many values in one variable, in a fixed order.
Creating a List
Write the items inside square brackets [], separated by commas:
Example
fruits = ["mango", "banana", "apple"]
marks = [78, 92, 65, 88]
mixed = ["Ali", 19, True]
print(fruits)
print(len(marks))['mango', 'banana', 'apple'] 4
Lists are ordered (items keep their position), changeable, and they allow duplicates.
Accessing Items
Like strings, list items have index numbers starting at 0:
Example
fruits = ["mango", "banana", "apple", "guava"]
print(fruits[0])
print(fruits[-1])
print(fruits[1:3])mango guava ['banana', 'apple']
Changing Items
Example
fruits = ["mango", "banana", "apple"]
fruits[1] = "orange"
print(fruits)['mango', 'orange', 'apple']
Adding and Removing Items
Example
cart = ["rice", "sugar"]
cart.append("tea") # add at the end
cart.insert(0, "flour") # add at position 0
print(cart)
cart.remove("sugar") # remove by value
last = cart.pop() # remove and return the last item
print(cart)
print("Removed:", last)['flour', 'rice', 'sugar', 'tea'] ['flour', 'rice'] Removed: tea
| Method | What it does |
|---|---|
append(x) | Adds x at the end |
insert(i, x) | Adds x at index i |
extend(other) | Adds all items of another list |
remove(x) | Removes the first x |
pop(i) | Removes item at index i (last one if empty) |
clear() | Removes all items |
index(x) | Position of x |
count(x) | How many times x appears |
Sorting
Example
marks = [78, 92, 65, 88]
marks.sort()
print(marks)
marks.sort(reverse=True)
print(marks)
names = ["Zara", "ali", "Bilal"]
print(sorted(names, key=str.lower))[65, 78, 88, 92] [92, 88, 78, 65] ['ali', 'Bilal', 'Zara']
sort() changes the list itself. sorted() gives back a new sorted list and leaves the original alone.
Looping Through a List
Example
subjects = ["Maths", "Physics", "English"]
for s in subjects:
print("I study", s)I study Maths I study Physics I study English
Copying a List
Writing b = a does not copy a list. Both names point to the same list, so changing one changes the other. Use b = a.copy() to make a real copy.
List Comprehension
A list comprehension builds a new list in one short line:
Example
prices = [100, 250, 400]
with_tax = [p * 1.18 for p in prices]
print(with_tax)
marks = [45, 78, 32, 90]
passed = [m for m in marks if m >= 50]
print(passed)[118.0, 295.0, 472.0] [78, 90]
Read it as: "give me p * 1.18 for every p in prices".
Exercise
Exercise
Which method adds an item to the end of a list?
