Python Basics: Your First Programs
Lists and Tuples
In this lesson you will
- Create lists and change them with common methods
- Slice, sort and loop over lists
- Explain how tuples differ from lists
Introduction
One variable holds one value. But what if you have a shopping list, or the scores of thirty students? A list holds many values in order, in one variable.
Creating and reading lists
Write a list in square brackets, separated by commas. Items are numbered from 0, just like characters in a string.
A list can hold anything, even a mix of types, and other lists:
Changing a list
Unlike strings, lists can be changed.
Quick quiz
Which method adds an item to the end of a list?
Searching, counting and sorting
sorted(x) returns a new list and leaves the original alone. x.sort() changes the list in place and returns nothing. Beginners often mix these up.
Looping over lists
Lists are shared, not copied
When you assign a list to another name, both names point to the same list.
Use .copy() or list(a) when you need an independent copy.
Tuples
A tuple is like a list that cannot be changed. Use round brackets. Tuples are good for values that belong together and should stay fixed, such as coordinates.
You can unpack a tuple (or list) into separate variables in one line:
Quick quiz
What is the main difference between a list and a tuple?
Try it yourself
Given the list of test scores below, print the highest score, the lowest score, the average (rounded to 1 decimal place) and the scores in order from high to low.
Summary
- A list is an ordered, changeable collection in square brackets, indexed from 0.
- Use
append,insert,remove,popanddelto change lists, andsorted()or.sort()to order them. - Loop with
for item in items, orenumeratefor index and value. Assigning a list does not copy it: use.copy(). - A tuple
( , )cannot be changed, and unpacking splits it into variables.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading