print [x * x for x in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] print [shumai * shumai for shumai in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] print [x for x in range(10)] print [42 for x in range(10)] print [x*x for x in range(10) if x >= 5] import random print random.randrange(100) print [random.randrange(6)+1 for i in range(100)] flavors = ["vanilla", "chocolate", "red velvet", "durian", "cinnamon", "~mystery~"] print random.choice(flavors) print random.sample(flavors, 2) print flavors random.shuffle(flavors) print flavors t = ("alpha", "beta", "gamma", "delta") print t t[-2] t[1:3] t.append("epsilon") t[2] = "bravo" moon_counts = {'mercury': 0, 'venus': 0, 'earth': 1, 'mars': 2} moon_counts.items() tuple([1, 2, 3, 4, 5]) list((1, 2, 3, 4, 5)) s = set(["alpha", "beta", "gamma", "delta", "epsilon"]) print type(s) print s s = {"alpha", "beta", "gamma", "delta", "epsilon"} print type(s) print s for item in s: print item [item[0] for item in s] s.add("omega") print s "beta" in s "emoji" in s source_list = ["it", "is", "what", "it", "is"] without_duplicates = set(source_list) print without_duplicates import time, random values = range(9999) values_set = set(values) start_list = time.clock() for i in range(1000): random.randrange(99999) in values end_list = time.clock() start_set = time.clock() for i in range(1000): random.randrange(99999) in values_set end_set = time.clock() print "1000 random checks on list: ", end_list - start_list, "seconds" print "1000 random checks on set: ", end_set - start_set, "seconds" import sys print "size of list: ", sys.getsizeof(values) print "size of set: ", sys.getsizeof(values_set) t = dict() # same as t = {} print type(t) items = [("a", 1), ("b", 2), ("c", 3)] t = dict(items) print t us_presidents = ["carter", "reagan", "bush", "clinton", "bush", "obama"] prez_lengths = {} for item in us_presidents: prez_lengths[item] = len(item) print prez_lengths prez_length_tuples = [(item, len(item)) for item in us_presidents] print "our list of tuples: ", prez_length_tuples prez_lengths = dict(prez_length_tuples) print "resulting dictionary: ", prez_lengths prez_lengths = dict([(item, len(item)) for item in us_presidents]) print prez_lengths prez_lengths = {item: len(item) for item in us_presidents} print prez_lengths state_names = ["alabama", "alaska", "arizona", "arkansas", "california"] state_pop = [4849377, 736732, 6731484, 2966369, 38802500] combo = zip(state_names, state_pop) print combo state_pop_lookup = dict(zip(state_names, state_pop)) print state_pop_lookup elements = ["hydrogen", "helium", "lithium", "beryllium", "boron"] index = 0 for item in elements: print index, item index += 1 # the range() function returns a list from 0 up to the specified value enumerated_elements = zip(range(len(elements)), elements) print "enumerated list: ", enumerated_elements # now, iterate over each tuple in the enumerated list... for index_item_tuple in enumerated_elements: print index_item_tuple[0], index_item_tuple[1] for index, item in enumerated_elements: print index, item # this code: print "with zip/range/len:" for index, item in zip(range(len(elements)), elements): print index, item print "\nwith enumerate:" # ... can also be written like this: for index, item in enumerate(elements): print index, item def first(t): return t[0] first("all of these wonderful characters") print first grab_index_zero = first grab_index_zero("all of these wonderful characters") how_many_things_are_in = len how_many_things_are_in(["hi", "there", "how", "are", "you"]) import random def say_hello(): greetz = ["hey", "howdy", "hello", "greetings", "yo", "hi"] print random.choice(greetz) + "!" say_hello() def thrice(func): for i in range(3): func() # let's try it out... thrice(say_hello) def first(t): return t[0] elements = ["hydrogen", "helium", "lithium", "beryllium", "boron"] # a new list containing the first character of each string map(first, elements) [first(item) for item in elements] def greater_than_ten(num): return num > 10 numbers = [-10, 17, 4, 94, 2, 0, 10] filter(greater_than_ten, numbers) [item for item in numbers if greater_than_ten(item)] # the regular way def first(t): return t[0] # the "shorthand" way first = lambda t: t[0] # test it out! first("cheese") # squish combines the first item of its first parameter with the last item of its second parameter squish = lambda one, two: one[0] + two[-1] squish("hi", "there") # you could also write "squish" the longhand way, like this: #def squish(one, two): # return one[0] + two[-1] elements = ["hydrogen", "helium", "lithium", "beryllium", "boron"] map(lambda x: x[0], elements) numbers = [-10, 17, 4, 94, 2, 0, 10] filter(lambda x: x > 10, numbers) elements = ["hydrogen", "helium", "lithium", "beryllium", "boron"] elements.sort() print elements elements = ["hydrogen", "helium", "lithium", "beryllium", "boron"] print sorted(elements) # with .sort() numbers = [52, 54, 108, 13, 7, 2] numbers.sort(reverse=True) print numbers # with sorted() numbers = [52, 54, 108, 13, 7, 2] sorted(numbers, reverse=True) states = [ ('Alabama', 4849377), ('Alaska', 736732), ('Arizona', 6731484), ('Arkansas', 2966369), ('California', 38802500) ] # doesn't sort based on population! sorted(states) def get_second(t): return t[1] sorted(states, key=get_second) sorted(states, key=lambda t: t[1]) word_counts = {'it': 123, 'was': 48, 'the': 423, 'best': 7, 'worst': 13, 'of': 350, 'times': 2} sorted(word_counts) word_counts.items() sorted(word_counts.items(), key=lambda x: x[1]) sorted(word_counts.items(), key=lambda x: x[1], reverse=True) import urllib import json query_url = "http://api.openweathermap.org/data/2.5/forecast/daily?id=5128581&cnt=5&units=imperial" resp = urllib.urlopen(query_url).read() data = json.loads(resp) data days = data['list'] # each item in "days" is a dictionary with weather information for that day days[0] import datetime def timestamp_to_date(dt): return datetime.datetime.fromtimestamp(dt).date().isoformat() cleaned = list() for item in days: new_item = { 'date': timestamp_to_date(item['dt']), 'max_temp': item['temp']['max'], 'min_temp': item['temp']['min'], 'humidity': item['humidity'], 'description': item['weather'][0]['description'] } cleaned.append(new_item) cleaned sorted(cleaned, key=lambda x: x['max_temp']) by_temp = sorted(cleaned, key=lambda x: x['max_temp']) by_temp[0]['date'] sorted(cleaned, key=lambda x: x['max_temp'])[0]['date'] filter(lambda x: "rain" not in x['description'], cleaned) [day for day in cleaned if "rain" not in day['description']] set([day['description'] for day in cleaned]) dict([(day['date'], day['humidity']) for day in cleaned]) date_humidity = {day['date']: day['humidity'] for day in cleaned} date_humidity date_humidity['2015-07-17']