Python List and Loop Flashcards
Lists
can contain multiple or individual items
You can put items of any type in a list
Separate with commas and surround with [ ]
Lists are kept in order
Lists example:
meals = [“artichokes”, “bbq”, “chili”, “donuts”]
*Lists can contain duplicates
[“artichokes”, “bbq”, “chili”, “donuts”, “bbq”]
Good to use plural nouns for variable name (meals not meal)
Accessing Items list by Index:
meals = [“artichokes”, “bbq”, “chili”, “donuts”]
meals = [‘artichokes’, ‘bbq’, ‘eggs’]
print(meals[1])
bbq
list = [‘artichokes’, ‘bbq’, ‘eggs]
print (list.index(‘bbq’))
1
Adding to Lists
list. append( ) ## append elem at end
list. append(‘shemp’) ## append elem at end
list. insert(0, ‘xxx’) ## insert elem at index 0
list. extend([‘yyy’, ‘zzz’]) ## add list of elems at end
How to code adding
list = [ ] ## Start as the empty list
list. append(‘a’) ## Use append() to add elements
list. append(‘b’)
print(list)
>[‘a’, ‘b’,]
or:
print(list.append(‘a’))
More Adding methods:
list = [‘larry’, ‘curly’, ‘moe’]
list. append(‘shemp’) ## append elem at end
list. insert(0, ‘xxx’) ## insert elem at index 0
list. extend([‘yyy’, ‘zzz’]) ## add list of elems at end
print (list)
[‘xxx’, ‘larry’, ‘curly’, ‘moe’, ‘shemp’, ‘yyy’, ‘zzz’]
Removing from Lists
Remove item from end: pop with nothing in parentheses
list. remove(‘curly’) ## search and remove that element
list. pop(1) ## removes and returns ‘larry’
How to code to remove:
list = ['larry', 'curly', 'moe'] print(list.remove("curly")) or list.remove("curly") print(list) >None >list = ['larry', 'moe']
or
remove = list.remove(“curly”)
print(list)
more code to remove:
list = ['larry', 'curly', 'moe'] print(list.pop(1)) or list.pop(1) print(list) >curly >list = ['larry', 'moe']
or
pop = list.pop( )
print(list)
Sorting Lists
list.sort( )
print(sorted(list))
The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed.
How to code: Sorting
list = [5, 1, 4, 3]
print(sorted(list))
>[1, 3, 4, 5]
or list = [5, 1, 4, 3] list.sort print(list) >[1, 3, 4, 5]
Reverse sorting code:
list = [2, 1, 3, 5, 6, 4]
list.sort(reverse = True)
print(list) # >[6, 5, 4, 3, 2, 1]
or print(sorted(list, reverse = True)) # >[6, 5, 4, 3, 2, 1]
Getting List: Length
len(list)
Note: syntax is different than for append, pop, and sort
With len, list_name goes in parentheses
How to code: Length
meals = [‘hummus’, ‘ice cream’, ‘grits’]
print(len(meals))
>3
Loops
They’re great for repeating code
You decide the condition that ends the loop
FOR and IN
The for construct – for var in list – is an easy way to look at each element in a list (or other collection). Do not add or remove from the list during iteration.
The in construct on its own is an easy way to test if an element appears in a list (or other collection) – value in collection – tests if the value is in the collection, returning True/False.