Python Basics Flashcards
Two ways of creating an empty list.
empty_list = [] empty_list = list()
Format for accessing an element in a list by indexing?
listname[index_number]
How can a matrix be represented in a list.
By nesting the list:
B = [ [ 1, 2 ], [ 0 ,4 ] ]
Format for slicing a list?
Which items get included?
mylist[ 0 : 3 ]
0, 1, 2
(Not inclusive of last index)
What is the format for slicing a list to the end or from the beginning?
to end -> mylist[ 2 : ]
from beginning -> mylist[ : 5 ]
Format and function of using the step feature when list slicing?
myList[ 1::2 ] - goes to end of list, returning every other element
myList[ 1::3 ] - goes to end of list, returning every third element
Format for returning the index of an item in a list?
myList.index(element_name)
Returns first occurence.
Options for adding items to a list?
new_list = myList.append( new_element ) new_list = myList + [ new_element ]
Format for sorting a list in place and non-muted?
sorted( myList ) - non-muted
myList.sort() - in place
Format of dictionaries?
dictname = {key1:value1, key2:,value2, …}
Two things to keep in mind about dictionaries?
They are unordered.
The keys must be unique.
Format to access the value of a given key?
myDict[ key_name ]
How to get list of keys from a dictionary?
myDict.keys( )
How to get a list of values from a dictionary?
myDict.values( )
How to sort a dictionary by the keys?
sorted( myDict )