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)