for i in sequence:#for loop blockprint i
Official Python documentation: https://docs.python.org/2/tutorial/controlflow.html#for-statements
Official Python documentation: https://docs.python.org/2/library/functions.html#range
Conditions must evaluate to a boolean (true or false) result. For example: x == 5
if condition:#if blockprint "if condition was true"
You can include zero or more elif
statements and zero or one else
statements.
if condition1:#if blockprint "if condition1 was true"elif condition2:#elif block 2print "elif condition2 was true"elif condition3:#elif block 3print "elif condition3 was true"else:#else blockprint "elif condition3 was true"
Official Python documentation: https://docs.python.org/2/tutorial/controlflow.html#if-statements
Functions allow you to perform the same action without copying code by simply calling the function.
"""Description of function goes here"""#performs actions heremanipulated_input = input_things*2#returns the following to be used in the code that calls this functionreturn manipulated_input
Official Python documentation: https://docs.python.org/2/tutorial/controlflow.html#defining-functions
The list data structure is a mutable sequence type created with square brackets.
my_list = #empty list#[2]#[2,4,8]#[2,4,8]print #access the first element of a list
List elements can be assigned and reassigned singly:
my_list = #[1,2,3,4]= "at index 3" #[1,2,3,"at index 3"]
Or as a slice:
= #[1, 'at index 1', 'at index 2', 'at index 3']
Creates a new list from a range (two indices) of elements in the original list. The start index is inclusive, the end index is exclusive.
new_list =
Evaluates to True if val is in the list, False if it is not.
contains = val in my_list
Official Python documentation: https://docs.python.org/2/library/stdtypes.html#typesseq
Find the index of the first occurrence of val in a list. It is an error if val is not in the list.
i =
Counts the number of times a value appears in a list.
cnt =
Removes the first occurrence of a value from a list.
Removes and returns the last element from a list.
last =
Official Python documentation: https://docs.python.org/2/tutorial/datastructures.html#more-on-lists
Sets are a valuable type because you can easily manipulate them and they have no repeated items. Keep in mind this data structure is not ordered though, meaning the data you enter will not stay in the order you enter it.
To create a set:
some_data =other_data = #there must be elements in the curly brackets, {} means something else
Official Python documentation: https://docs.python.org/2/library/stdtypes.html#set
This will add an element to your set. Remember, the order in which you add is irrelevant!
books =print books #this prints: set(['Quidditch Through the Ages'])
There are several different ways to remove an element from a set.
my_plan =#this will choose and remove one arbitrary elementprint my_plan #here, this prints: set(['play', 'sleep', 'study', 'eat'])#this would work even if 'play' wasn't in setprint my_plan #this prints: set(['sleep', 'study', 'eat'])my_plan = my_plan - #this would work even if 'sleep' wasn't in setprint my_plan #this prints: set(['study', 'eat'])#this would NOT work if 'eat' wasn't in set, KeyErrorprint my_plan #this prints: set(['study'])
Identify if something is in your current set.
books ='Star Wars' in books #evaluates as False'Lord of the Rings' in books #evaluates as True
Update your current set by adding the new elements from other sets.
data =other_data =data |= other_dataprint data #this yields the output: set([1, 2, 3, 4, 5, 6])
Identify what elements sets have in common.
my_music =cafe_music =shared_music = my_music & cafe_musicprint shared_music #this prints: set(['jazz']}
Identify what elements are not in one set when compared to another.
my_music =cafe_music =unique_to_me = my_music - cafe_musicprint unique_to_me #this prints: set(['classical', 'rock'])unique_to_cafe = cafe_music - my_musicprint unique_to_cafe #this prints: set(['blues', 'hipster'])
A dictionary is an unordered mapping of keys to values.
To create a dictionary:
empty_dict =days_dict =dict_of_lists =
Values from a dictionary can be retrieved using the key.
print #prints 18
But trying to access a key that does not exist will cause an error.
print #throws KeyError: tuesday
However you can use the dictionary method get to provide a default value.
print #prints 0print #prints 17
You can also test if a key is in a dictionary.
'tuesday' in days_dict #evaluates to false#evaluates to true
To add to a dictionary assign to a key that does not exist. Or use the update method.
= 8
Assigning to a key already in a dictionary changes the mapping.
= 17+= 2
To remove an element from a dictionary use the del keyword.
del
Use the keys() and values() iterate through a dictionary.
for day in :print day,for count in :print count
Shortcut 1: Iterating through a dictionary is equivalent to using the keys() method.
for day in days_dict:print day,
Shortcut 2: Use the items() method to iterate through key,value pairs at the same time.
for day,count in :print day,count
There are two simple ways to sort a list. For either you can provide functions for comparison, key finding, and can supply a boolean to specify if the sort should be reversed.
Modifies the existing list. Returns None.
my_list =# my_list is now sorted [-100, 0, 100, 200]# my_list is now reverse sorted [200, 100, 0, -100]
Official Python documentation: https://docs.python.org/2/tutorial/datastructures.html#more-on-lists
Returns a new copy of the list that has been sorted.
students =sorted_students =print students# [('jane', 'B', 12), ('john', 'A', 15), ('dave', 'B', 10)]print sorted_students# [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
Official Python documentation: https://docs.python.org/2/library/functions.html#sorted
An immutable ordered sequence of values. You can create new tuples, access individual elements but cannot change the elements in an existing tuple.
Tuples are created using parenthesis and by separating the elements with commas.
You can access elements of a tuple in the same way you access elements of a list.
Official Python documentation: https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences
Itemgetter is a function that returns a function. Use it to make functions that are used to get elements from a tuple. This can be useful when supplying a key function to a sort.
from operator import itemgetterstudent_score= ('Robert', 8)get_name =get_score =# evaluates to 'Robert'# evaluates to 8student_scores =# sort the list of student scores by the students name# [('Alice', 9), ('Robert', 8), ('Tina', 7)]sorted_student_scores =
Official Python documentation: https://docs.python.org/2/library/operator.html#operator.itemgetter