Boston Python Workshop 8/Friday/Lists

Defining lists

>>> your_list = ["a", "b", "c"] >>> type(your_list)  >>> my_list = [.1, 5, -7, 15]

Length

>>> len(your_list) 3 >>> len(my_list) 4

Containment

>>> "a" in your_list True >>> "z" in your_list False >>> .5 not in my_list True

Accessing individual elements

>>> your_list[0] 'a' >>> your_list[1] 'b' >>> your_list[2] 'c' >>> your_list[3] Traceback (most recent call last): File " ", line 1, in IndexError: list index out of range >>> your_list ['a', 'b', 'c']

Appending elements

>>> your_list.append("d") >>> len(your_list) >>> your_list[3] 'd'

How would we create an empty list?

>>> her_list = [] >>> len(her_list) 0

replacing elements (band example)

>>> names = ["Alice", "Amy"] >>> names.append("Adam") >>> names ['Alice', 'Amy', 'Adam'] >>> names[0] = "Jimmy" # not cutting it on drums >>> names ['Jimmy', 'Amy', 'Adam'] >>> names[2] = "Rachel" # too much time with groups >>> names ['Jimmy', 'Amy', 'Rachel']

Remember:

= is for assignment == is for comparison

>>> names.append("Tim") # sax >>> names.append("Bob") # trumpet >>> names.append("Alexis") # french horn >>> names ['Jimmy', 'Amy', 'Rachel', 'Tim', 'Bob', 'Alexis'] >>> len(names) 6

how do you get elements off the end of a list? Use negative numbers!

>>> names[-1] 'Alexis' >>> names[-2] 'Bob' >>> names[-3] 'Tim'

lists and strings are similar - length - stuff in an order

>>> my_name[0] 'J' >>> my_name[-1] 'a'

Review

>>> fruits = ["apples", "bananas", "oranges"] >>> fruits[0] 'apples' >>> fruits[-1] 'oranges' >>> fruits[0] = "plums" >>> fruits.append("cherries") >>> fruits ['plums', 'bananas', 'oranges', 'cherries'] >>> len(fruits) 4 >>> "apples" in fruits False >>> "cherries" in fruits True