Python Lists

Outside Resources:

TheNewBoston Video – Lists

w3schools Lists

Tutorials Point Interactive Tutorial – Lists

LearnPython.org Interactive Tutorial – Lists

Snakify.org Interactive Tutorial – Lists


Lists are similar to strings, because they are both collections of items. Strings are like a list of characters, but lists can contain any type of items.

Lists are surrounded with [square brackets]. Items are separated by commas. Examples:

veggies = ["carrot", "potato", "lettuce"]
squares = [1, 4, 9, 16, 25]

Notice that lists can store text items or integer items, or various other types.

Lists can be indexed and sliced using square brackets:

#index to return a single item
veggies[0]
veggies[-1]

#slice to return a smaller list of items
squares[2:4]

You can print an entire list or print a single item from a list.

print(veggies)
print(veggies[2])

Lists can be added together, similar to the way you concatenate strings using the “+” operator.

desserts = ["cake", "pie", "ice cream"]
foods = desserts + veggies
junkfood = ["chips", "candy"] + ["fries", "cookies"]

print(junkfood)

Creating an empty list:

animals = []

You can also use the “+=” operator to add a list to an existing list. Make sure you remember the square brackets:

animals += ['lion', 'mouse', 'shark']
animals += ['starfish', 'wolf']
animals += ['dolphin']
animals += ['emu']
print(animals)

If you forget the square brackets, you’ll either get an error, or an undesired result. Try it to see what happens.

#this line runs, but it doesn't do what you expect.
animals += "crocodile"
print(animals)

#this line will throw an error: try it and read the error message.
animals += 100

Another way to add an item to the list is with the append() list method:

places = ['France', 'China', 'Ghana']
places.append('New Zealand')
print(places)

You can also use the remove() method to remove an item:

cakes = ['carrot', 'cheese', 'spice', 'chocolate']
cakes.remove('carrot')

#note: the -= operator doesn't work with lists.

Just like you did with strings, you can check the length of a list using the len() function:

print len(foods)
foods_count = len(foods)
if len(foods) > 0:
	print("This list has a non-zero length.")
else:
	print("This list is empty.")

Notice how you can use the len() function as part of a condition. Sometimes you don’t know if there are any items in a list, and you’ll get errors if you try something like foods[0] when there is actually no item in the list. In that case, check if the list is empty first, then index the list if it’s not empty.

If you want an easier way to check if a list is empty, Python provides something faster. When you use a list as a condition, it returns True if it contains any items, and it returns False if it’s empty. Example:

if foods:
	print("This list is NOT empty")
else:
	print("This list IS empty.")

In other words, if len(foods) > 0 is the same as if foods.
Non-empty collections are “truthy” in Python. Empty collections are “falsy.”

Try those previous examples with both empty lists and non-empty lists to see the difference.

List functions

Lists can run many functions on themselves. Examples:

numbers = [4, 10, 3, 7, 4, 2, 7, 4]

numbers.sort()
print(numbers)

#find the location (index) of a specific item
print(numbers.index(10))

#count how many times an item appears
print(numbers.count(4))

Checking if an item is in the list

You can use the in keyword to check if something is in a list. A phrase like “item in list” will evaluate to either True or False, so it is used in conditions.

spices = ['salt', 'paprika', 'pepper']

if 'pepper' in spices:
	print("Pepper is in the list.")
else:
	print("Pepper is NOT in the list.")

You can also use “not in” to check if an item isn’t in a list.

Try simply typing some “in” conditions into your Python console window to see the True/False results:
(These won’t seem to do anything if you type them in the code editor and run the program)

numbers = [1, 3, 7, 100]
5 in numbers
1 in numbers
"salad" in numbers
3 not in numbers
"3" in numbers

That last one will remind you that there’s a difference between 3 (int) and “3” (str).

Removing items

Lists have a list_name.remove() function for removing items. Note that the “-=” operator won’t work on lists.

fruits = ["apple", "kiwi", "mango", "kiwi"]
fruits.remove("kiwi")
print(fruits)

If your list contains more than one of the same item, only one instance will be removed, as you can see if you tried the previous example.

You can use the del (delete) keyword to delete an item number:

colors = ['orange', 'purple', 'black', 'pink']

#delete item #2:
del colors[2]

Lists (and other collections) also have a pop() method that can delete an item number:

names = ['Han', 'Leia', 'Luke', 'Chewie', 'Ben']

#delete item #0 from names:
names.pop(0)

Bonus: the pop() method returns the deleted item, so your code can use that information. For example, if you want to save the deleted items in a new list:

uneaten = ['apple', 'cake', 'chips', 'fig', 'chicken']
eaten = []

# Remove first two items from uneaten, 
# and add them to eaten:
eaten.append(uneaten.pop(0))
eaten.append(uneaten.pop(0))
print('Not eaten yet:', uneaten)
print('Already eaten: ', eaten)

Combining with variables

The examples above are using “literal” text (quoted text) in most cases, but you can also include the stored information from variables to a list. Remember not to use quotes around variable names.

favorite = "raspberry"
fruits += [favorite]

Square brackets still go around the variable name when adding it to a list. You are adding a new list (containing one item) to the existing list. Try to think about the difference between square brackets and quotes: square brackets are for list items and index numbers, whereas quotes surround literal string (text) data.

The index of a string can be a variable that contains an integer:

x = 2
print(foods[x])
x += 1
print(foods[x])

Converting to list
Sometimes it’s useful to convert some other types of object into lists using the list() function.

# this is a dictionary (dict) object:
states = {'ND': 1889, 'IA': 1846, 'NY': 1778}

# this gives just the state abbreviations
keys = states.keys()

#convert that to a list instead
keys = list(states.keys())

#now you can use a list method such as sort()
keys.sort()
print(keys)

#Another example: convert string to list
word = "spaghetti"
list_word = list(word)
# Notice what this looks like when printed
print(list_word)

You can split a string into a list:

# split by spaces
s = "This is a sentence."
words = s.split(' ')

# split by commas
string_data = "spoon,fork,spork"
words = string_data.split(',')

You can also join a list of words together to make a string:

words = ['hearts', 'spades', 'clubs', 'diamonds']
# connect all the words with ", " between each word
text = ", ".join(words)

join() is a string function. Any string (such as “, “) can use itself to connect all of the items in a list and return the resulting string.