Python List Operations

In the last lesson you learned Introduction to Lists. So now you know how to put a bunch of values together in one place. But a list is only useful if you can actually do things with it. You need to read one item out. You need to change an item. You need to ask how many items are inside. You need to check if something is even there. That is what list operations are. Let me walk you through the everyday ones, one at a time.

๐Ÿค” Why You Need List Operations

Say you have a list of names for a chat group:

friends = ["Alex", "Riya", "Arjun"]

The list just sitting there does nothing. The real work starts when you ask questions of it. Who is the first person? How many people are in the group? Is โ€œRiyaโ€ in here? Can I show every name on screen? Each of those is a list operation. They are the small, everyday moves you make on a list. Once you know them, you can build almost anything with lists.

๐Ÿ”ข Read an Item by Index

Every item in a list has a position number. We call that position the index. Here is the part that trips people up. Counting starts at 0, not 1. So the first item is at index 0. The second is at index 1. And so on.

This code reads single items out of the list by their position:

friends = ["Alex", "Riya", "Arjun"]
print(friends[0])
print(friends[1])
print(friends[2])

Output

Alex
Riya
Arjun

So friends[0] gives you โ€œAlexโ€ because Alex sits at position 0. You put the index inside square brackets right after the list name.

Python also lets you count from the end using negative numbers. So -1 means the last item. And -2 means the second to last. This is handy when you do not know how long the list is but you want the last thing.

This code grabs the last item without caring about the length:

friends = ["Alex", "Riya", "Arjun"]
print(friends[-1])
print(friends[-2])

Output

Arjun
Riya

Caution

If you ask for an index that does not exist, like friends[5] on a three-item list, Python stops and raises an IndexError. Always make sure the position you ask for is really there.

โœ๏ธ Change an Item

A list is changeable. That means you can replace an item after you make the list. You point at the position you want. Then you assign a new value to it.

This code swaps the second name for a different one:

friends = ["Alex", "Riya", "Arjun"]
friends[1] = "Sara"
print(friends)

Output

['Alex', 'Sara', 'Arjun']

See what happened? friends[1] used to be โ€œRiyaโ€. We assigned โ€œSaraโ€ to that spot. So now the list holds โ€œSaraโ€ there instead. The list itself stays the same list. It just has one item changed.

๐Ÿ“ Check the Length with len()

Often you need to know how many items are in a list. Maybe you want to show โ€œ3 people in this groupโ€. The len() function counts the items for you and gives back a number.

This code asks how many friends are in the list:

friends = ["Alex", "Riya", "Arjun"]
count = len(friends)
print(count)
print(f"There are {count} people in the group.")

Output

3
There are 3 people in the group.

You pass the list to len() and it returns the count as a plain number. One thing worth remembering. The last valid index is always len(list) - 1. The list above has length 3. So the last item sits at index 2. That is because counting started at 0.

โž• Join Lists with +

Sometimes you have two separate lists and you want one combined list. The + operator joins them end to end. This is called concatenation, which just means sticking one list after another.

This code joins a list of close friends and a list of new friends into one:

close_friends = ["Alex", "Riya"]
new_friends = ["Arjun", "Sara"]
everyone = close_friends + new_friends
print(everyone)

Output

['Alex', 'Riya', 'Arjun', 'Sara']

The + makes a brand new list. It holds all the items from the first list followed by all the items from the second. The two original lists stay exactly as they were.

โœ–๏ธ Repeat with *

The * operator repeats a list a given number of times. This is great when you want a list filled with the same starting value.

This code makes a list of three zeros. Say you want three rounds of a game that all start at score 0:

scores = [0] * 3
print(scores)
dashes = ["-"] * 5
print(dashes)

Output

[0, 0, 0]
['-', '-', '-', '-', '-']

So [0] * 3 means โ€œtake this one-item list and repeat it three timesโ€. You get a fresh list with the contents copied that many times. It saves you from typing the same value over and over.

๐Ÿ” Check if a Value Is Inside with in

Before you do something with an item, you often want to know if it is even in the list. The in operator answers that with a simple True or False.

This code checks whether certain names are in the group:

friends = ["Alex", "Riya", "Arjun"]
print("Riya" in friends)
print("Sara" in friends)
print("Sara" not in friends)

Output

True
False
True

So "Riya" in friends is True because Riya really is in the list. "Sara" in friends is False because she is not. You can flip it with not in to ask the opposite question. This is perfect inside an if statement. For example, you only add someone if they are not already there.

๐Ÿ” Loop Over a List

Most of the time you do not want just one item. You want to go through every item and do something with each. A for loop walks through the list one item at a time, from first to last.

This code prints a greeting for every friend in the list:

friends = ["Alex", "Riya", "Arjun"]
for name in friends:
print(f"Hello, {name}!")

Output

Hello, Alex!
Hello, Riya!
Hello, Arjun!

Read it almost like English. โ€œFor each name in friends, print a greeting.โ€ On the first turn name is โ€œAlexโ€. Then โ€œRiyaโ€. Then โ€œArjunโ€. The loop stops on its own when the list runs out. You do not deal with index numbers at all here. That is why this is the cleanest way to visit every item.

If you also need the position number while you loop, enumerate() gives you both the index and the item together:

friends = ["Alex", "Riya", "Arjun"]
for position, name in enumerate(friends):
print(f"{position}: {name}")

Output

0: Alex
1: Riya
2: Arjun

Here enumerate() hands you the index in position and the value in name on each turn. Use this when the position actually matters, like numbering a list on screen.

โš ๏ธ Common Mistakes

A few things tend to bite people early. Watch for these.

  • Forgetting that counting starts at 0. The first item is friends[0], not friends[1].
friends = ["Alex", "Riya", "Arjun"]
# โŒ Avoid: thinking index 1 is the first item
print(friends[1]) # prints "Riya", not "Alex"
# โœ… Good: index 0 is the first item
print(friends[0]) # prints "Alex"
  • Asking for an index that is past the end. A three-item list only has indexes 0, 1, and 2. Asking for friends[3] raises an IndexError.

  • Mixing up len() and the last index. len(friends) is 3, but the last item is at index 2. The last index is always len(list) - 1.

  • Thinking + adds the lists item by item. It does not. With lists, + joins them end to end. [1, 2] + [3, 4] gives [1, 2, 3, 4], not [4, 6].

โœ… Best Practices

Small habits that keep your list code clean and clear.

  • Loop with for item in list when you just need each value. Reach for enumerate() only when you actually need the position too.
  • Use in to check before you act, so you do not assume an item is there when it is not.
  • Reach for len() instead of counting items by hand. It is always right, even when the list grows or shrinks.
  • Give your list a clear plural name like friends or scores, so for name in friends reads naturally.

๐Ÿงฉ What Youโ€™ve Learned

โœ… Read any item by its index, where counting starts at 0 and negative numbers count from the end.

โœ… Change an item by assigning a new value to its position.

โœ… Count items with len(), and remember the last index is len(list) - 1.

โœ… Join two lists with + and repeat a list with *.

โœ… Check if a value is present with in (and not in for the opposite).

โœ… Visit every item with a for loop, and use enumerate() when you also need the position.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    Given friends = ['Alex', 'Riya', 'Arjun'], what does friends[0] return?

    Why: Counting starts at 0, so index 0 is the first item, which is 'Alex'.

  2. 2

    What does len(['a', 'b', 'c', 'd']) return?

    Why: len() counts the items in the list, and this list has four items.

  3. 3

    What is the result of [1, 2] + [3, 4]?

    Why: The + operator joins lists end to end, giving one combined list [1, 2, 3, 4].

  4. 4

    Given friends = ['Alex', 'Riya'], what does 'Sara' in friends return?

    Why: Sara is not in the list, so the in operator returns False.

๐Ÿš€ Whatโ€™s Next?

You can now do the everyday moves on a list. Next you will meet the built-in tools that lists carry with them, like adding, removing, and sorting items.

List Methods

Share & Connect