Test Review - Lists
Test Review - Lists
LISTS
General
Functions
Concatenation
We can add lists together using + or we can use * to multiply many lists together
Examples:
L = [5,6]
S = [3,2]
L + S [5,6,3,2]
L*3 [5, 6, 5, 6, 5, 6]
Loops and Lists
for x in list:
This allows us to step through a list, with x taking on the next element in the list.
Recall lists can store any data type, including other lists.
To access data inside a list that is inside a list, first we need to index the outer list, then the inner list.
Example:
L = [ 10, 6, [4, 7, 9] ]
If we call the 2nd index of L, you will access the whole list.
L[2] [4, 7, 9]
If we then take the index 1 of that it will access the element at location [1] of the list, L[2].
L[2][1] 7
'''List Review'''
##mylist = ['a','b','c']
##print(mylist)
Methods
Methods are like functions, that work only on certain data types. A list method follows the list it will
work on. Methods have a period, then the name, then parentheses and arguments inside.
Listobject.methodname(arguments if any)
Know the following methods, how they work and what they return:
list.index(X) returns the index of the first occurrence of X in list
list.count(X) returns the number of occurrences of X in list
list.append(X) adds X to the end of the list
list.insert(i, X) adds X at position i
list.remove(X) removes the first occurence of X
list.pop(i) deletes & returns item list[i], while list.pop() deletes & returns the last item
list.reverse() reverses the list
list.sort() sorts the list