Chapter 4: Lists

The “Variable Avalanche” Crisis

Chaitanya walks into the computer lab looking like he hasn’t slept. His eyes are red. He drops his bag on the floor with a heavy thud.

Aditi Ma’am: Rough night, Chaitanya?

Chaitanya: I was up until 3 AM working on the School Cricket Team roster. The coach wants me to track the names of all 11 players. So I created variables: player1, player2, player3… all the way to player11.

Aditi Ma’am: Okay…

Chaitanya: But then he added 4 substitutes! So I had to make player12, player13… And now he wants to track their scores too! Do I need score1, score2score15? That’s 30 variables just for one team! My code looks like a phone book!

Aditi Ma’am: That is the classic “Variable Avalanche.” You are trying to juggle 30 balls at once. Why not just put them all in a Box?

Chaitanya: A box?

Aditi Ma’am: In Python, we call it a List. A list is a single variable that can hold an ordered sequence of many values. Instead of player1, player2, etc., you just have one variable: team.

Creating a List

Aditi Ma’am: To build a list, we use square brackets [].

Python

team = ['Kohli', 'Dhoni', 'Rohit', 'Bumrah']
scores = [100, 50, 45, 10]

Chaitanya: So team is the variable?

Aditi Ma’am: Yes. And the names inside are the Items. You can put anything in a list: strings, integers, floats, or even other lists!

Python

mixed_bag = ['Chaitanya', 15, 98.5, ['Math', 'Science']]

Chaitanya: Whoa. A list inside a list?

Aditi Ma’am: Yes. That’s called a List of Lists. It’s like putting a pencil box inside your backpack.

Indexing: Finding Your Spot

Chaitanya: Okay, I have a list. How do I get just one player out of it?

Aditi Ma’am: You use an Index. Think of it like the roll numbers in a class register. But there is one catch: Python starts counting at 0, not 1.

Chaitanya: Zero? That’s weird.

Aditi Ma’am: It’s a computer science tradition. The first item is at index 0. The second is at index 1.

Python

>>> team = ['Kohli', 'Dhoni', 'Rohit', 'Bumrah']
>>> team[0]
'Kohli'
>>> team[1]
'Dhoni'
>>> team[3]
'Bumrah'

Chaitanya: What happens if I ask for team[4]? There are 4 players.

Aditi Ma’am: Try it.

Chaitanya:

Python

>>> team[4]
IndexError: list index out of range

Chaitanya: Ouch. “Out of range.”

Aditi Ma’am: Exactly. If you have 4 items, the indices are 0, 1, 2, and 3. There is no index 4. That’s like asking for Roll Number 50 in a class of 40 students.

Negative Indexes (Counting Backwards)

Aditi Ma’am: Python has a cool trick. If you want the last item but don’t know how long the list is, use a negative number.

Python

>>> team[-1]
'Bumrah'
>>> team[-2]
'Rohit'

Aditi Ma’am: -1 is the last item. -2 is the second-to-last item.

Slicing: Taking a Group Photo

Chaitanya: What if I want the first two batsmen? Do I have to say team[0] and team[1] separately?

Aditi Ma’am: You can Slice the list. It’s like taking a group photo of just a section of the line. Syntax: list[start : end]

Aditi Ma’am: But be careful: It includes the start index, but goes up to (but not including) the end index.

Python

>>> team[0:2]
['Kohli', 'Dhoni']
  • Starts at index 0 (‘Kohli’).
  • Stops before index 2 (Excludes ‘Rohit’).

Chaitanya: That’s slightly confusing.

Aditi Ma’am: Think of it like this: end - start tells you how many items you’ll get. 2 - 0 = 2 items.

Shortcuts:

  • team[:2] (Start at the beginning).
  • team[1:] (Start at index 1 and go to the very end).

Changing the List (The Mutable Bookshelf)

Chaitanya: Oh no! ‘Rohit’ is injured. I need to replace him with ‘Pant’. Do I have to rewrite the whole list?

Aditi Ma’am: No. Lists are Mutable. That means “changeable.” Just overwrite the specific slot.

Python

>>> team[2] = 'Pant'
>>> team
['Kohli', 'Dhoni', 'Pant', 'Bumrah']

Chaitanya: Can I add new players?

Aditi Ma’am: Yes. You can use Concatenation with + to join two lists.

Python

>>> team = team + ['Jadeja', 'Ashwin']
>>> team
['Kohli', 'Dhoni', 'Pant', 'Bumrah', 'Jadeja', 'Ashwin']

Aditi Ma’am: Or, you can remove items using the del statement. It’s like erasing a name from the whiteboard.

Python

>>> del team[1]
>>> team
['Kohli', 'Pant', 'Bumrah', 'Jadeja', 'Ashwin']

(Dhoni is gone!)

Loops and Lists (The Roll Call)

Chaitanya: Ma’am, printing the whole list looks ugly: ['Kohli', 'Pant', ...]. I want to print a nice list like:

  1. Kohli
  2. Pant

Aditi Ma’am: Use a for loop. It works perfectly with lists.

Python

for player in team:
    print(player)

Chaitanya: That prints the names. But how do I get the numbers 1, 2, 3?

Aditi Ma’am: You can loop through the Range of the list’s length.

Python

for i in range(len(team)):
    print('Player ' + str(i) + ': ' + team[i])

Aditi Ma’am: Or, even better, use the enumerate() function. It gives you both the index AND the item.

Python

for index, player in enumerate(team):
    print('Player ' + str(index) + ': ' + player)

The in and not in Operators

Chaitanya: I need to check if ‘Kohli’ is in the team before I print the lineup. Do I have to loop through everyone?

Aditi Ma’am: No. Just ask Python directly using in.

Python

>>> 'Kohli' in team
True
>>> 'Tendulkar' in team
False

Chaitanya: That reads just like English! “Is Kohli in team?”

Aditi Ma’am: Exactly. And you can use not in to check if someone is missing.

Python

if 'Tendulkar' not in team:
    print('Missing the legend!')

Multiple Assignment Trick

Aditi Ma’am: Chaitanya, look at this cool shortcut. Suppose you have a list of student details: student = ['Chaitanya', 15, 'Red House']. You want to put them into separate variables. The Old Way:

Python

name = student[0]
age = student[1]
house = student[2]

The Python Way:

Python

name, age, house = student

Chaitanya: Whoa! It unpacked the list?

Aditi Ma’am: Yes. But the number of variables must match the list length exactly, or it will crash.

Methods (List Tools)

Aditi Ma’am: Lists have special functions attached to them called Methods. Think of them as tools built into the bookshelf.

1. Finding an Index (index()) Chaitanya: Where is ‘Bumrah’ in the list?

Python

>>> team.index('Bumrah')
2

2. Adding to the End (append()) Aditi Ma’am: A new student joins the class.

Python

>>> team.append('Shami')

3. Inserting in the Middle (insert()) Aditi Ma’am: The Captain wants ‘Gill’ to bat at position 1.

Python

>>> team.insert(1, 'Gill')

4. Sorting (sort()) Chaitanya: Can I arrange them alphabetically?

Python

>>> team.sort()

Aditi Ma’am: Note: This changes the list permanently. You can’t undo it easily. And you can’t sort a list that has both numbers and words mixed together. Python doesn’t know if ‘Five’ is greater than 5.

Example Program: Magic 8-Ball with a List

Aditi Ma’am: Remember the Magic 8-Ball program from the Functions chapter? It was 20 lines of if...elif...elif....

Chaitanya: Yeah, it was a pain to type.

Aditi Ma’am: With a list, we can do it in 3 lines.

Python

import random

messages = ['It is certain',
    'It is decidedly so',
    'Yes definitely',
    'Reply hazy try again',
    'Ask again later',
    'Concentrate and ask again',
    'My reply is no',
    'Outlook not so good',
    'Very doubtful']

print(messages[random.randint(0, len(messages) - 1)])

Chaitanya: That is so much cleaner! random.randint picks a random index, and the list gives me the answer.

Mutable vs. Immutable (The Trap)

Scene: Aditi Ma’am draws a picture of a box on the whiteboard.

Aditi Ma’am: Chaitanya, this is the trickiest part of lists. Pay attention.

Strings are Immutable (Unchangeable):

Python

name = 'Zophie'
name[0] = 'S' # ERROR! You can't change a string.

Lists are Mutable (Changeable):

Python

numbers = [1, 2, 3]
numbers[0] = 99 # Works! [99, 2, 3]

Aditi Ma’am: But here is the trap. When you assign a list to a variable, you aren’t storing the list. You are storing a Reference (a pointer) to the list.

Chaitanya: Like a shortcut icon on my desktop?

Aditi Ma’am: Exactly. If you copy the shortcut, both shortcuts point to the same program.

Python

>>> spam = [0, 1, 2, 3]
>>> cheese = spam # Copied the reference, NOT the list!
>>> cheese[1] = 'Hello!'
>>> spam
[0, 'Hello!', 2, 3]

Chaitanya: Wait! I changed cheese. Why did spam change?

Aditi Ma’am: Because spam and cheese are both pointing to the same list in memory. If you change one, you change the other.

Chaitanya: How do I make a real separate copy?

Aditi Ma’am: You need the copy module.

Python

import copy
spam = ['A', 'B', 'C']
cheese = copy.copy(spam) # Creates a brand new list
cheese[1] = 42
# Now spam is still ['A', 'B', 'C']

Summary

Aditi Ma’am: That’s Lists.

  1. List: [1, 2, 3]
  2. Index: Position (starts at 0).
  3. Slice: A part of a list [start:end].
  4. Reference: Variables hold a link to the list, not the list itself.

Chaitanya: I’m going to go rewrite the cricket roster. I think I can do it in 5 lines now instead of 50.

Aditi Ma’am: That’s the spirit. Next up: Dictionaries. That’s where things get really powerful.

Leave a Comment

💬 Join Telegram