Lesson 11 of 30
In progress
Lists: many values in one place
Store many values in one ordered collection, read them by position and slice, and avoid the shared-reference bug that catches every beginner.
Ten students means ten variables, unless you use a list. A list holds an ordered collection under one name, which is the difference between code that scales and code you copy-paste until it becomes unmaintainable.
What you will learn
- Create a list, read items by index and slice a section.
- Change, add and remove items safely.
- Recognise when two names point at the same list.
A list is an ordered shelf
Items sit in a fixed order and each has a position. Square brackets create a list, and commas separate the items.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(scores)
print(len(scores))
print(scores[0])
print(scores[-1])
Press Run to see the output.
scores[0] is the first item because Python counts from zero. scores[-1] is the last, scores[-2] the second last. len() gives the count, which is always one more than the highest valid index. Asking for scores[5] in a five-item list raises IndexError, and that error is information: your index is outside the shelf.
Lists may mix types, and they may nest. Mixing is legal but usually a sign you wanted a dictionary or a tuple; module 3 ends with the guidance.
Slicing takes a section
A slice uses start:stop and excludes the stop, just like range.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(scores[1:3])
print(scores[:2])
print(scores[3:])
print(scores[::2])
print(scores[::-1])
Press Run to see the output.
The first slice gives items at index 1 and 2. Omitting the start means "from the beginning"; omitting the stop means "to the end". A step of 2 skips every other item, and a step of -1 reverses the list. Slicing never raises for out-of-range bounds; it clamps, which is why scores[10:] is simply empty.
Change, add and remove
Lists are mutable, so you can replace an item in place.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
scores.append(64)
print(scores)
del scores[1]
print(scores)
Press Run to see the output.
append adds one item to the end and del removes by position. The next lesson covers the rest of the methods — insert, remove, pop, sort — because there are enough of them to deserve their own page. For now, notice that these operations change the list itself; none of them returns a new list.
Membership and iteration
in asks whether a value appears, and for visits each item in order.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print("Ravi" in names)
print("Sam" in names)
for name in names:
print("Hello,", name)
Press Run to see the output.
Membership on a list checks items one by one, so it slows down as the list grows. For a few hundred items that is irrelevant; for thousands of repeated checks, a set is the right tool, which is why lesson 14 introduces it.
The alias trap
Assignment does not copy a list. Two names can point at the same shelf, and changing one changes what the other sees.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(original)
print(alias)
print(original is alias)
Press Run to see the output.
Both print [1, 2, 3, 4] because there is only one list. is confirms they are the same object. When you want an independent copy, ask for one explicitly: copy = original[:] or copy = list(original). That is a shallow copy, which matters once the items are themselves lists — lesson 15 returns to that.
Looping over a list while removing items skips elements, because the indices shift under you. for score in scores: scores.remove(score) looks reasonable and quietly leaves items behind. Build a new list, or loop over a copy with for score in scores[:].
Given a list of daily temperatures, print the highest, the lowest and the average without using max, min or sum. Start from the first item rather than from zero, so negative temperatures work.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
for temp in temps:
if temp > highest:
highest = temp
if temp < lowest:
lowest = temp
total += temp
print("High:", highest)
print("Low:", lowest)
print("Average:", round(total / len(temps), 1))
Press Run to see the output.
Starting from temps[0] is the important detail. Starting highest at zero would fail for a week of sub-zero readings.
Recap
- A list is ordered, mutable and indexed from zero; negative indexes count from the end.
- Slices use
start:stopand exclude the stop; out-of-range slices clamp instead of failing. - Assignment aliases;
list(items)oritems[:]makes a shallow copy.
Next, you will use the list methods that do the daily work: adding, removing, searching and sorting.
What is the difference between a list and a tuple?
Why does indexing start at zero?
Progress is saved in this browser only. No account, no email.