Lists, Lists Operators and Built-in Functions

Types

What's a type? What are the types that we've seen so far? →

A type is a set of values. It's a way of classifying them. Some examples of types that we've learned include… →

Types of Types

Types can actually be classified as well. Like types of types! How are the following types related, and what do they have in common?

Sequences

We've seen numeric types, like int, float and complex. Another kind/classification of type is a sequence. A sequence:

Sequences support operations like:

We've Seen This Before

What data type have we seen that supports these operations?

A string is an ordered sequence of characters. It is a sequence type. It supports:

"blubbins?"[0] #index, first element -> "b" 
"blubbins?"[-1] #index, last element -> "?"
"blubbins?"[1:4] #slices -> "lub"
"blubbins?"[4:] #slices -> "bins?"
"what the " + "blubbins?" # concatenates -> "what the blubbins?"
"blubbins?" * 2 # repeats -> "blubbins?blubbins?"

Lists

A list is another sequence type.

#  a list of ints
stuff = [1, "one", 2, "two"]

List Literals

Constructing a list using a list literal looks like this:

["some", "stuff", "between", "brackets"]

Printing Lists

You can pass lists directly to the built-in print function. It will output the list as if it were a string literal:

>>> a = [2, 3, 5, 7]
>>> print(a)
[2, 3, 5, 7]

You can also use str() or string formatting to create a string representation of a list:

>>> a = [2, 3, 5, 7]
>>> print("Some numbers in a list: %s" % a)
Some numbers in a list: [2, 3, 5, 7]

Built-in List Operators and Functions

Because a list is just another sequence type many of the built-in operators and functions that work with strings behave similarly with lists.

Indexing Operations

What will the following code output? →

import math
land_of_ooo = ["jake", "finn", "pb"]
a = -1
print(land_of_ooo[0])
print(land_of_ooo[2])
print(land_of_ooo[a])
print(land_of_ooo[int(math.sqrt(1))])
jake
pb
pb
finn

Indexing Operations Continued

What will the following code output? →

import math
land_of_ooo = ["jake", "finn", "pb"]
a = -1
print(land_of_ooo[3])
print(land_of_ooo[1.0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not float

Indexing Operations Continued Some More!

Using the list below, How would you retrieve "homer"… once using a positive index, and another time using a negative index? →

simpsons = ["marge", "homer", "lisa"]
simpsons[1]
simpsons[-2]

Indexing Operations Summary

Mutability

Unlike strings, however, lists are mutable. That means that you can reassign a value at an index! What will the following code print out? →

>>> a = [3, 4, 5]
>>> a[0] = "surprise"
>>> print(a)
['surprise', 4, 5]

Indexing Into a List of Lists

Lists can be composed of any objects, including other lists:

stuff = [['foo', 'bar', 'baz'], [1, 2, 3], [0.25, 0.5, 0.75]]

List of Lists Exercises

Using the same list:

stuff = [['foo', 'bar', 'baz'], [1, 2, 3], [0.25, 0.5, 0.75]]
stuff[1][2]
stuff[2][0] = 0

Iterating Over a List

Just like iterating over a sequence of characters…

Iterating Over a List Example

What will the following for loop print out? →

some_boolean_values = [True, True, False]
for b in some_boolean_values:
	print(b)
True
True
False

Iterating Over a List of Lists

How do you think we can print out every element in a line of its own in this list of lists?

stuff = [['foo', 'bar', 'baz'], [1, 2, 3], [0.25, 0.5, 0.75]]
"""NESTED LOOPS!"""
stuff = [['foo', 'bar', 'baz'], [1, 2, 3], [0.25, 0.5, 0.75]]
for inner_list in stuff:
	for element in inner_list:
		print(element)

Slicing

Slicing also works on lists. What will the following code output? →

colors = ["red", "green", "blue", "taupe"]
print(colors[0:2])
print(colors[2:])
print(colors[:3])
print(colors[0:100])
['red', 'green']
['blue', 'taupe']
['red', 'green', 'blue']
['red', 'green', 'blue', 'taupe']

Slicing Summary

Again… like slicing strings.

Equality Operators

Equal or not equal?

print([1, 2, 3] == [1, 2, 3])
print(['a', 'b', 'c'] == [1, 2, 3])
print(['a', 'b', 'c'] != [1, 2, 3])
True
False
True

Greater Than, Less Than

""" What boolean values do these statements return?"""
['a', 'b', 1, 2] > ['b', 'b', 1, 2]
[5, 2] < [5, 2, 1]
['x', 'y', 'z'] < ['x', 'a', 'z']
False
True
False

Addition and Multiplication

Multiplication and addition of lists are similar to the same operations on strings. What will the following code output? →

toppings = ["mushrooms", "peppers", "onions"]
numbers = [2, 3, 5, 7]
print(toppings + numbers)
print(toppings * 2)
print(numbers * 2)
["mushrooms", "peppers", "onions", 2, 3, 5, 7]
["mushrooms", "peppers", "onions", "mushrooms", "peppers", "onions"]
[2, 3, 5, 7, 2, 3, 5, 7]

Addition and Multiplication Summary

len()

You can still use the built-in function, len, on lists. What do you think the following code will output? →

a = ["foo", "bar", "baz"]
b = []
c = ["foo", "bar", "baz", [1, 2, 3]]
print(len(a))
print(len(b))
print(len(c))
3
0
4

Looking for something?

Testing for membership within a list is similar to testing for a character in a string. Use the in operator. It returns True if the operand on the left is an element in the list on right. What does the following code print out? →

print('c' in ['a','b', 'c'])
print('c' not in ['a', 'b', 'c'])

breakfast = ["oatmeal", "tofu scramble", "ramen"]
if "ramen" in breakfast:
	print("ramen for breakfast")
else:
	print("wise decision")
True
False
ramen for breakfast

Deleting List Items

You can delete list items using del statement:

What does the following code print out? →

vegetables = ["broccoli", "cauliflower", "brownie sundae", "carrot"]
del vegetables[2]
print(vegetables)
['broccoli', 'cauliflower', 'carrot']

Some Exercises

Potential Solutions

numbers = [1, 2, 3, 4, 11, 12, 13, 14]
print_out_number = False
for n in numbers:
	if print_out_number:
		print('%s!' % (n))
	print_out_number = not print_out_number
import math
def half_a_list(items):
	half_index = math.floor(len(items) / 2)
	return items[:half_index]