Sets are unordered data types whose elements are unique. Therefore, adding a value to a set that already has it, does nothing.
Sets can be created with comma separated elements enclosed in {} in Python 2.7 or greater.
Very often, one will make a list and use the set() function to eliminate duplicates.
>>> list_a = [0, 3, 2, 0, 2, 7]
>>> set_a = set(list_a)
>>> print set_a
set([0, 2, 3, 7])
>>> set_b = {1, 2, 1, 3}
>>> print set_b
set([1, 2, 3])
Sets have an add method, which like append for lists, adds an element to a set.
As we have already seen, an element in a list can be other lists.
Lists inside of a list are referred to as nested
The following is a list of lists:
game_board = [
['O', 'X', ' '],
[' ', 'X', ' '],
[' ', ' ', ' '],
]
This can be indexed successively with game_board[0][1]
A list can be appended to a list as well
mary_shopping_list = ['apples', 'bananas', 'chicken', 'ice cream']
fran_shopping_list = ['ice cream', 'beef', 'peppers', 'apples']
bob_shopping_list = ['chicken', 'peppers']
family_shopping_list = []
family_shopping_list.append(mary_shopping_list)
family_shopping_list.append(fran_shopping_list)
family_shopping_list.append(bob_shopping_list)
print family_shopping_list
for shop_list in family_shopping_list:
for food_item in shop_list:
print food_item
What if we want to flatten the family shopping list?
What if we want the food items in the family shopping list to be unique?
One of the most common and useful nested data structures,
is a list of dictionaries
card_a = {
'suit': 'spades',
'number': 4,
}
card_b = {
'suit': 'hearts',
'number': 8,
}
hand = [card_a, card_b]
print 'The hand contains:'
for card in hand:
print 'A', card['number'], 'of', card['suit']
A dictionary can also contain values that are themselves
other data types, such as lists.
Let's revisit the group of to do lists and find a better representation:
mary_shopping_list = ['apples', 'bananas', 'chicken', 'ice cream']
fran_shopping_list = ['ice cream', 'beef', 'peppers', 'apples']
bob_shopping_list = ['chicken', 'peppers']
family_shopping_list = {
'mary': mary_shopping_list,
'fran': fran_shopping_list,
'baby': bob_shopping_list,
}
for name, shop_list in family_shopping_list.items():
print name, 'needs to buy: ', shop_list
# Changing this later can be accomplished with
family_shopping_list['fran'].append('strawberries')
Now the to do lists can be indexed or modified by name
Lists, dictionaries, and other data types are all
a means of combination.
They can be freely combined to create the
data structure needed for a particular problem.
Eg. A list of dictionaries with lists
all_tweets = [
{
'author': 'mary',
'handle': '@hadalittlelamb',
'date': '2013-01-22',
'tweets': [
'at Loco Pops enjoying a Raspberry Sage popsicle',
'Learning Python is so much fun',
],
},
]
character = {
'level': 'beginner',
'health': 100,
}
def injure(character, damage):
character['health'] = character['health'] - damage
if character['health'] < 0:
character['health'] = 0
def heal(character, amount):
character['health'] = character['health'] + amount
if character['health'] > 100:
character['health'] = 100
Python is a not a purely functional language, but it can be used (and is commonly used) for functional programming.
There are four functions that are used for functional programming: Range, Filter, Map, and Reduce
One commonly used, higher order function
(that is a Python builtin) is called map
# Define any function
def sqaure(number):
return number ** 2
# Pass the function to map along with an iterable
squares = map(square, range(10))
Write a function that prints the double
of every number from 0 to 10 using a for loop
Write a function that prints the double
of every number from 0 to 10 using a range
Write a function that prints the double
of every number from 0 to 10 using a map
Write a map that takes in a list and appends "or I'll be a monkey's uncle" to every item in that list. (input: [1,4], output: ["1 or I'll be a monkey's uncle"], "2 or I'll be a monkey's uncle"])
Choose among any of these projects:
(Resources available on the next page)
Search the Web | python-duckduckgo library to get started. Download duckduckgo.py and put it in the same directory as your code. Use the query() function it provides to begin. (HINT: Results are often empty, but 'related' list usually has a few hits.) |
Encryption | Read about the Caesar Cipher or find a similarly simple encryption mechanism online. You should find the ord() and chr() functions helpful, as well as the modulus operator '%' |
Command Line Game | This might be a text adventure with paragraphs of text followed by a series of choices for the user. A choice maps to another node in the story (another paragraph with choices). You might try storing the paragraphs separately in a text file. The format might be something different, such as a series of "rooms", each with a description, for the user to explore by entering commands such as "go west". Examples of these kinds of games are Colossal Cave Adventure and Zork |
Automate the Boring Stuff with Python | Online book of 'practical programming for total beginners'. |
Python.org Documentation | Official Python Documentation |
Think Python | Online and print book with exercises. |
Learn Python the Hard Way | Online and print book with exercises |
Google's Python Class | Video lectures coupled with exercises |
New Coder | Ideas for slightly larger projects and resources to get you started. Projects include accessing API's, scraping pages, writing IRC bots, and others. |
Girl Develop It | Local workshops, events, and coding sessions |
Please fill out this survey to let us know how you felt about this class, and if there's any ways we can improve.