We've looked at variables and we know that they hold values assigned to them. For example, if we wanted to store the name of our friend we write friend = "Michael". What if we have 3 more friends? We can write friend_1 = "James", friend_2 = "Laura", friend_3 = "Kimani". Aaah excellent! We have stored four friends.
What about 50? Ooops... creating 50 variables and assigning values to them seems very tiring. What about 1,000 or 50,000? You can see the issue, right? Well, now we need a solution for that: a manageable approach to storing our friend contacts. Voila! Python lists solve this exact problem.
Let's make this concrete. Imagine you're a teacher and you want to store the names of students in your class. You start enthusiastically:
student_1 = "Alice Wanjiku"
student_2 = "Brian Ochieng"
student_3 = "Catherine Muthoni"
student_4 = "David Kimani"
student_5 = "Grace Akinyi"
This feels manageable, right? But wait... what happens when you want to print all the names? You'd have to write:
print(student_1)
print(student_2)
print(student_3)
print(student_4)
print(student_5)
Hmm, that's already getting repetitive. And what if you want to find a specific student? You'd need something like:
target_name = "Grace Akinyi"
if target_name == student_1:
print("Found the student!")
elif target_name == student_2:
print("Found the student!")
elif target_name == student_3:
print("Found the student!")
# ... and so on
You're probably thinking, "There has to be a better way!" And you're absolutely right. Now imagine if you had 50 students. Or 200. You'd spend more time creating variables than actually teaching!
This is where we realize that our approach doesn't scale. We need something that can grow with our needs without making our code a nightmare to write and maintain.
In that sense, a list is similar to a string, except a string can hold only characters. A list can hold any Python object. The elements of a list do not all have to be of the same type.
Let's transform our student storage problem:
students = ["Alice Wanjiku", "Brian Ochieng", "Catherine Muthoni", "David Kimani", "Grace Akinyi"]
Look at that! One line instead of five. But here's the beautiful part - this approach works whether you have 5 students or 5,000 students.
Let's break down what we see:
The right-hand side of the assignment statement is a literal list
The elements of the list appear within square brackets ([]), and commas separate the elements.
When we print this list:
print(students)
We get:
['Alice Wanjiku', 'Brian Ochieng', 'Catherine Muthoni', 'David Kimani', 'Grace Akinyi']
Before we go deeper, let's see how lists represent real-world collections. Have you ever made a shopping list? That's a list! Your phone's contact list? Also a list! Your playlist on Spotify? You guessed it - another list!
Now, let's create some lists that represent real situations:
Your shopping list:
shopping_list = ["Milk", "Bread", "Eggs", "Rice", "Cooking Oil"]
print(shopping_list)
["Milk", "Bread", "Eggs", "Rice", "Cooking Oil"]
Grades for your mathematics tests:
[85, 92, 78, 88, 95]
["Milk", "Bread", "Eggs", "Rice", "Cooking Oil"]
Daily temperatures this week:
weekly_temperatures = [23.5, 26.8, 24.2, 27.1, 25.9]
print(weekly_temperatures)
[23.5, 26.8, 24.2, 27.1, 25.9]
Aaah excellent. Do you notice something interesting? Lists can hold different types of data!
Strings : "Milk", "Bread"
Integers : 85, 92, 78
Floating point values : 23.5, 26.8
As a matter of fact, you can even mix them in one list:
student_profile = ["John Mwangi", 20, 3.7, "Computer Science"]
print(student_profile)
["John Mwangi", 20, 3.7, "Computer Science"]
We have strings ("John Mwangi" and "Computer Science"), integer (20) and a floating point value (3.7). This list represents a student's name, age, GPA, and major all in one place!
Now here's where things get really interesting. We've created our list, but how do we get specific items from it? This is where we need to understand a fundamental concept called indexing.
Think of it like people standing in a queue - the first person is at position 0, the second person is at position 1, and so on. In programming, each item in a list has a unique index that tells you exactly where that item sits.
To access an item in a list, we use this format:
list_name[index_number]
The square brackets [ ] are crucial here - they tell Python "I want to access a specific item at this position." Inside the brackets, you put the index number of the item you want.
Here's something that trips up many beginners: Python starts counting from 0, not 1. This is called zero-based indexing.
Why 0? It's a computer science convention that makes memory calculations more efficient. Imagine you're standing at the starting point of a race track. You haven't taken any steps yet - that's position 0. After one step forward, you're at position 1, and so on.
Let's visualize this with our students list:
students = [
"Alice Wanjiku",
"Brian Ochieng",
"Catherine Muthoni",
"David Kimani",
"Grace Akinyi"
]
Here's how Python sees the positions:
Index: 0 1 2 3 4
Item: "Alice Wanjiku" "Brian Ochieng" "Catherine Muthoni" "David Kimani" "Grace Akinyi"
So when we want the first student, we ask for index 0. When we want the second student, we ask for index 1. Let's see this in action:
students = [
"Alice Wanjiku",
"Brian Ochieng",
"Catherine Muthoni",
"David Kimani",
"Grace Akinyi"
]
print(students[0]) # Alice Wanjiku (first student - index 0)
print(students[1]) # Brian Ochieng (second student - index 1)
print(students[2]) # Catherine Muthoni (third student - index 2)
print(students[3]) # David Kimani (fourth student - index 3)
print(students[4]) # Grace Akinyi (fifth student - index 4)
Alice Wanjiku
Brian Ochieng
Catherine Muthoni
David Kimani
Grace Akinyi
Notice the pattern? The index is always one less than the human-friendly position number.
Something important to understand: Python only accepts integers (whole numbers) as list indices. You cannot use decimals or fractions. This makes sense when you think about it - you can't have "the 2.5th item" in a list!
students = ["Alice Wanjiku", "Brian Ochieng", "Catherine Muthoni"]
print(students[0]) # ✓ Works - integer index
print(students[1]) # ✓ Works - integer index
print(students[1.5]) # ✗ Error! Cannot use decimal
print(students["first"]) # ✗ Error! Cannot use string
Alice Wanjiku
Brian Ochieng
Traceback (most recent call last):
File "/home/gitahi/trial.py", line 5, in <module>
print(students[1.5]) # ✗ Error! Cannot use decimal
~~~~~~~~^^^^^
TypeError: list indices must be integers or slices, not float
This is different from some other programming languages that might allow more flexible indexing, but Python keeps it simple and consistent.
Here's a really cool feature - Python also supports negative indices that count backwards from the end of the list:
students = [
"Alice Wanjiku",
"Brian Ochieng",
"Catherine Muthoni",
"David Kimani",
"Grace Akinyi",
]
print(students[-1]) # Grace Akinyi (last item)
print(students[-2]) # David Kimani (second to last)
print(students[-3]) # Catherine Muthoni (third from end)
students = [
"Alice Wanjiku",
"Brian Ochieng",
"Catherine Muthoni",
"David Kimani",
"Grace Akinyi",
]
print(students[-1]) # Grace Akinyi (last item)
print(students[-2]) # David Kimani (second to last)
print(students[-3]) # Catherine Muthoni (third from end)
This is incredibly useful when you want the last item but don't know exactly how many items are in the list:
students = [
"Alice Wanjiku",
"Brian Ochieng",
"Catherine Muthoni",
"David Kimani",
"Grace Akinyi",
]
# Get the last student without counting
last_student = students[-1]
print(f"The last registered student is: {last_student}")
The last registered student is: Grace Akinyi
You need to know how to find out how many items are in your list. We use the len() function:
students = [
"Alice Wanjiku",
"Brian Ochieng",
"Catherine Muthoni",
"David Kimani",
"Grace Akinyi",
]
total_students = len(students)
print(f"We have {total_students} students") # We have 5 students
We have 5 students
This is crucial because if you try to access an index that doesn't exist, Python will give you an error, the IndexError:
students = [
"Alice Wanjiku",
"Brian Ochieng",
"Catherine Muthoni",
] # 3 students, indices 0, 1, 2
print(students[0]) # ✓ Works
print(students[2]) # ✓ Works
print(students[3]) # ✗ Error! Index 3 doesn't exist
Alice Wanjiku
Catherine Muthoni
Traceback (most recent call last):
File "/home/gitahi/trial.py", line 9, in <module>
print(students[3]) # ✗ Error! Index 3 doesn't exist
~~~~~~~~^^^
IndexError: list index out of range
Let's explore different situations where indexing becomes powerful:
mathematics_scores = [85, 92, 78, 88, 95, 73, 89]
student_names = [
"Alice",
"Brian",
"Catherine",
"David",
"Grace",
"Emmanuel",
"Faith",
]
# Find Alice's score (first student, index 0)
alice_score = mathematics_scores[0]
print(f"Alice scored {alice_score} in mathematics")
# Find the last student's score
last_score = mathematics_scores[-1]
last_student = student_names[-1]
print(f"{last_student} scored {last_score} in mathematics")
Alice scored 85 in mathematics
Faith scored 89 in mathematics
week_days = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
]
temperatures = [23.5, 26.8, 24.2, 27.1, 25.9, 22.3, 24.7]
# Check Monday's temperature
monday_temp = temperatures[0]
print(f"Monday's temperature: {monday_temp}°C")
# Check weekend temperatures
saturday_temp = temperatures[5] # Index 5 for Saturday
sunday_temp = temperatures[6] # Index 6 for Sunday
print(
f"Weekend temperatures: Saturday {saturday_temp}°C, Sunday {sunday_temp}°C"
)
Monday's temperature: 23.5°C
Weekend temperatures: Saturday 22.3°C, Sunday 24.7°C
No comments yet
Be the first to share your thoughts on this article!