Chapter 2: Lists

List

face Josiah Wang

Let’s say you have 50 students in your class.

Say you need to write a program to read the students’ email addresses from a file (we will tackle reading files later!) Maybe you want to invite them all to your birthday party or something? (Don’t forget your lecturer!) 🥳🥳

With what we have covered so far, you might assign one variable to each student, maybe student1, student2, student3, student4, etc.

But having to manually name 50 variables? That is tedious work with all the repeated copying-and-pasting!

Is there a way to refer to the whole list of students as a group?

Lists to the rescue!

Fortunately, Python provides us with a built-in data type called list to represent a sequence of objects.

A list is, well, a list! A list can be expressed by enclosing the list of objects with square brackets, and separate each item in the list with commas.

students = ["Abraham", "Bella", "Connor", "Da-ming", "Enya"]

You can also use list() to construct a new list object (remember that everything is an object in Python, including lists!)

>>> characters = list("abc")    # converts the string into a list of characters
>>> print(characters)
['a', 'b', 'c']
>>> type(characters)
<class 'list'>

Good programming style: notice how I named my variables -- with the plural students and characters!