Lists Flashcards
Creating lists
List = [1,2,3]
Blist = list (4,5,6)
Converting to lists
List(‘cat’)
»> [‘c’, ‘a’, ‘t’]
Or
List(a_tuple). ->. Creates list of values in a_tuple
Splitting function
Birthday = ‘1/6/1952’
Birthday.split(‘/’)
»> [‘1’, ‘6’, ‘1952’]
Get a list item by using [offset]
Change value by offset
Starts at zero
List[2] = ‘b’
»> changes the 3rd value of list to ‘b’
Get a slice to extract items by offset range
List[::2]. ->. Starts at list beginning and goes by 2
List[1:8:3]. ->. Goes from item 2 to item 9, by 3’s
Appending lists
List.append(‘value’)
-> appends ‘value’ to end of list
Extend function
Merges one list with another
A = [1,2,3] B = [6,7,8]
A.extend(B)
»> [1,2,3,6,7,8]
”+=”
Functions like extend
Merges the items in the lists
(As opposed to append, which would have added the second list as a single list item
A=[1,2]. B=[3,4]
A += B. ->. [1,2,3,4]
A.append(B). ->. [1,2,[3,4]]
Insert() function
Adds an item before any offset in a list.
List.insert(3, ‘itema’)
Adds ‘itema’ before item #4
Del [ ] function
Deletes an item by offset
Del list[2]. -> deletes the third item in list
Remove ( ) function
Removes that item wherever in the list
List.remove(‘cat’). ->. Removes ‘cat’
“LIFO”
Last in first out
Data structure or stack.
Append() followed by pop()
“FIFO”
First in, first out
Data structure or stack
Pop(0)
Index(. ) function
List.index(‘value ‘) -> tells what offset an item is
‘Value ‘ in list
Returns True if the value is in list, else False
Count(. ) function
Counts how many times a particular value occurs in a list.
List.count(‘value’)
Sort() function
Sorts the list in place, changes the list
List.sort()
List.sort(reverse =True). - > reverse sorts
Sorted() function
Returns a sorted copy of the list
List_sorted = sorted(list)
Len() function
Returns the number of items in a list
Ways to copy lists
A = [1,2,3] B = A.copy() C = list(A) D = A[:]
B, C, D are copies of A, changing A does not change the rest and vica versa
Tuple
Immutable
Follow all items with a comma, except last item
Tuple unpacking
Assigning multiple variables at once
A_tuple = (1,2,3)
a,b,c = A_tuple
-> a is 1, b is 2, etc
Tuple() conversion function
Makes tuples of other things
Tuple(list)
Dictionary
Created by placing curly brackets around comma separated key:value pairs
Dict = {key:value1, …}