Chapter 9 - Lists

A list is a simple concept that can provide a lot of power in the world of computer programming. This chapter will cover some of the basics about lists. Lists will be covered more in depth in later chapters (especially the chapter on loops) as related topics are explored.

A list, known in some programming languages as an array or a vector, is simply a list of related data stored under a single variable name. Instead of using code like this:

name1 = "Bob"
name2 = "Sue"
name3 = "Jeff"
name4 = "Sally"

print(name1)
print(name2)
print(name3)
print(name4)

You can use code like this:

names = ["Bob", "Sue", "Jeff", "Sally"]

print(names[0])
print(names[1])
print(names[2])
print(names[3])

In the last code block, the variable names is of type list. So a list is just another data type, just like ints, floats, strings, and booleans are different data types. In this case, names is a list of strings containing four values. All four of these values are names. They might be names of students in a classroom or a list of friends on Facebook or Twitter. Lists are useful for storing data that is related in some way.

Using a List Index

The last code block uses syntax like names[0]. You might remember similar syntax from the chapter on strings where the square brackets [] can be used to get a character from a string. You might also remember that strings are 0-indexed, meaning that the position of the first character in a string is position 0. Lists work the same way. The list names has four values, so it has indexes 0, 1, 2, and 3. You can use indexes to get data (such as print(names[0])) or to set data (such as names[0] = "Alice"). Use the coding exercise below to practice using lists and indexes.

def print_person(name, age): print(name + " is " + str(age) + " years old") names = ["Bob", "Sue", "Jeff", "Sally", "Ryan", "Jeff"] ages = [14, 16, 13, 13, 17, 11] print(names) print(ages) print_person(names[0], ages[0]) print_person(names[1], ages[1]) print_person(names[2], ages[2]) print_person(names[3], ages[3]) print_person(names[4], ages[4]) print_person(names[5], ages[5]) names[0] = "Jordan" ages[0] = 97 print(names) print(ages) print_person(names[0], ages[0])

Common List Functions

Common List Functions
FunctionResult
list.append(value)Adds value to the end of list
list.insert(position, value)Inserts value into list at index position
list.remove(value)Removes the first instance of value from list
list.pop()Removes the last value from list and returns that value
list.index(value)Returns the index of the first instance of value, does not change list
len(list)Returns the total number of values in list, does not change list
list.count(value)Returns the number of times value is found in list, does not change list
list.sort()Sorts the items in list
list.reverse()Reverses the order of the items in list
str.join(list)Returns a string containing all the values in list, each value separated by str
str.split(separator)Returns a list containing all the values in str broken up by separator

Use the exercise below to play with these list functions.

names = ["Bob", "Sue"] print(names) names.append("Rob") print(names) names.insert(0, "Steve") print(names) names.insert(1, "Sue") print(names) names.remove("Sue") print(names) last = names.pop() print(last + " was removed from the end of the list by the pop function") print(names) index = names.index("Sue") print("Sue is at index " + str(index)) names.append("Jake") names.append("Sue") names.append("Rob") names.append("Steve") names.append("Steve") names.append("Rob") print(names) steve_count = names.count("Steve") print("Steve appears " + str(steve_count) + " times") names.sort() print(names) names.reverse() print(names) print(",".join(names)) print(", ".join(names)) print("|".join(names)) print(" | ".join(names)) string_data = "Alice, Bob, Jack, Jill, Eve, Steven, Tommy" list_data = string_data.split(", ") print(string_data) print(list_data)

Splitting Lists (Sublists)

In Python, splitting lists is done in the same way as splitting strings into substrings. You can review the chapter on strings for a more detailed explanation. Python uses some of the same syntax for lists and strings because strings, in a way, are really just lists of characters. The syntax is

sublist = list_name[ start_index(inclusive) : end_index(exclusive) ]

Use the exercise below to experiment with splitting lists

colors = ["red", "orange", "yellow", "green", "blue", "purple"] warm_colors = colors[0:3] cool_colors = colors[3:len(colors)] fav_colors = colors[3:5] fav_colors.append("teal") print(colors) print(warm_colors) print(cool_colors) print(fav_colors)

Range Function

The range function in Python can be used as a shortcut to generate a list of numbers. This is a very useful function and will show up in later chapters. There are three different ways to call the range function:

range(10) # Returns a list from 0 to 9
range(5, 10) # Returns a list from 5 to 9
range(10, 100, 2) # Returns a list of all even numbers from 10 to 98

The first example defines an exclusive ending point. The list starts at 0 and includes every number less than the ending point. The second defines an inclusive starting point and an exclusive ending point. The third defines an inclusive starting point, an exclusive ending point, and an interval between every adjacent number in the list. Use the exercise below to experiment with the range function. You will want to be very familiar with it; it will help a lot as you continue to learn Python.

indexes = range(1) # Change to be a list of 0 to 10 (inclusive) dice = range(1) # Change to be a list of 1 to 6 (inclusive) fives = range(1) # Change to be a list of all multiples of 5 from 5 to 100 (inclusive) # Don't change these print statements print(", ".join(map(str, indexes))) print(", ".join(map(str, dice))) print(", ".join(map(str, fives))) indexes = range(11) # Change to be a list of 0 to 10 (inclusive) dice = range(1, 7) # Change to be a list of 1 to 6 (inclusive) fives = range(5, 101, 5) # Change to be a list of all multiples of 5 from 5 to 100 (inclusive) # Don't change these print statements print(", ".join(map(str, indexes))) print(", ".join(map(str, dice))) print(", ".join(map(str, fives))) test_object("indexes") test_object("dice") test_object("fives") success_msg("Great job!")
  • For indexes, input one parameter
  • For dice, input two parameters
  • For fives, input three parameters

Review

For this exercise, there are 2 hidden lists: cities and states. Follow the instructions in the comments to manipulate these lists and print the values.

cities = ["Salem", "Salt Lake City", "Houston", "Miami", "San Diego"] states = ["MA", "UT", "TX", "FL", "CA"] def print_city(city, state): print(city + ", " + state) # Append "Chicago" to cities and "IL" to states # Insert "Atlanta" into cities at index 2 # Insert "GA" into states at index 2 # Remove "Salem" from cities and "MA" from states # Call the print_city function on all 6 values in cities and states def print_city(city, state): print(city + ", " + state) # Append "Chicago" to cities and "IL" to states cities.append("Chicago") states.append("IL") # Insert "Atlanta" into cities at index 2 # Insert "GA" into states at index 2 cities.insert(2, "Atlanta") states.insert(2, "GA") # Remove "Salem" from cities and "MA" from states cities.remove("Salem") states.remove("MA") # Call the print_city function on all 6 values in cities and states print_city(cities[0], states[0]) print_city(cities[1], states[1]) print_city(cities[2], states[2]) print_city(cities[3], states[3]) print_city(cities[4], states[4]) print_city(cities[5], states[5]) test_object("cities") test_object("states")
Use functions append, insert, and remove