Lists
- Ordered collection of “stuff”
- Similar to what’s called an ‘array’ in other languages.
- Although “stuff” doesn’t all have to be the same type.
[1, 'a', 3.14159]is a valid list.
- An example of a container in Python.
- is mutable (can be changed)
- strings are not mutable.
len(lst)returns the number of items on the list.- How to swap the values in two variables?
- Swap first and last elements of the list (in-class 9)
Useful list operations / methods
- Create list from “iterable” things
list("abc")list(range(5, 10))
- Avoid using
listas a variable name. - Merge lists together:
[1, 2, 3] + ['a', 'b', 'c']
- Grab a sublist:
lst = ['a', 'b', 'c', 'd', 'e', 'f']thenlst[2:5]
- Remove element from a list:
del lst[3]
- Append an item:
x = [1, 2, 3]thenx.append(4)- Notice that
[1, 2, 3] + 4doesn’t work to add single item.
- Insert an item at a specific location
lst.insert(3, 'q')
- Review other useful methods in zyBook 8.2 and 8.3
Index of out of bounds
- Show what causes index out of bounds errors
Multi-dimensional lists
- You can nest lists
[['George', 'Washington'], ['John', 'Adams'], ['Thomas', 'Jefferson']]
Modifying lists in loops.
-
Double all the values in a list
lst = [1, 3, 9, 17, 44, 21, 36, 14] for index, item in enumerate(lst): lst[index] = item *2 print(lst) - Return a new list that is double the old (without modifying the input). (in-Class 9)
- List comprehension
[i * 2 for i in lst][i.lower() for in words]-
[int(i) for i in inp.split()](One line of input with many numbers)my_list = [[5, 10, 15], [2, 3, 16], [100]] sum_list = [sum(row) for row in my_list] print(sum_list)
- Slices
lst[2:5]lst[-1]- Notice the difference between
lst[0]andlst[0:1]
- Build a new array that is the reverse of a given array. (in-class 9)
- Reverse an array ‘in place’ (in-class 9)
Tuples
-
Tuples are essentially immutable lists.
t = ('a', 'b', 'c') t[0] t[0] = 7 print(t) - Useful for binding items together as a single conceptual object:
(2010, 12, 1)- Using a tuple would have given us a means for returning a date from a function.
- go back and change the
tomorrowfunction.
- Notice that using
date[0]anddate[1]can be a bit ambiguous. -
Named Tuples address this:
Date = namedtuple('Date', ['year', 'month', 'day']) today = Date(2023, 9, 27) - The first parameter is the name that is displayed when printed.
- Named tuples are immutable. (You can’t change them, you need to create a new one.)
- Update
tomorrowto use named tuple.cd