tup = 4, 5, 6
tup
(4, 5, 6)
tup[0]
4
nested_tup = (4, 5, 6), (7, 8)
nested_tup
((4, 5, 6), (7, 8))
nested_tup[1]
(7, 8)
nested_tup[1][0]
7
tuple([4, 0, 2])
(4, 0, 2)
tup = tuple('string')
tup
('s', 't', 'r', 'i', 'n', 'g')
tup[0]
's'
tup = tuple(['foo', [1, 2], True])
tup
('foo', [1, 2], True)
tup[2] = False
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-22-c7308343b841> in <module>() ----> 1 tup[2] = False TypeError: 'tuple' object does not support item assignment
tup[1]
[1, 2]
tup[1].append(3)
tup
('foo', [1, 2, 3], True)
(4, 'foo', True) + (6, False) + ('bar',)
(4, 'foo', True, 6, False, 'bar')
('foo', 'bar') * 4
('foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar')
tup = (4, 5, 6)
tup
(4, 5, 6)
a, b, c = tup
a
4
tup = (4, 5, (6, 7))
tup
(4, 5, (6, 7))
a, b, (c, d) = tup
a
4
c
6
seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
seq
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
for a, b, c in seq:
print a, b, c
1 2 3 4 5 6 7 8 9
for a in seq:
print a
(1, 2, 3) (4, 5, 6) (7, 8, 9)
a = (1, 1, 2, 2, 2, 3, 4, 2)
a.count(2)
4
a_list = [2, 3, 7, None]
a_list
[2, 3, 7, None]
tup = ('foo', 'bar', 'baz')
b_list = list(tup)
b_list
['foo', 'bar', 'baz']
b_list.append('dwarf')
b_list
['foo', 'bar', 'baz', 'dwarf']
b_list.insert(1, 'red')
b_list
['foo', 'red', 'bar', 'baz', 'dwarf']
b_list.pop(1)
'red'
b_list
['foo', 'bar', 'baz', 'dwarf']
b_list.append('apple')
b_list
['foo', 'bar', 'baz', 'dwarf', 'apple']
b_list.remove('apple')
b_list
['foo', 'bar', 'baz', 'dwarf']
b_list.remove('bar')
b_list
['foo', 'baz', 'dwarf']
'foo' in b_list
True
a_list + b_list
[2, 3, 7, None, 'foo', 'baz', 'dwarf']
a_list.extend(b_list)
a_list
[2, 3, 7, None, 'foo', 'baz', 'dwarf']
a = [7, 2, 5, 1, 3]
a
[7, 2, 5, 1, 3]
a.sort()
a
[1, 2, 3, 5, 7]
b = ['saw', 'small', 'he']
b.sort(key = len)
b
['he', 'saw', 'small']
import bisect
c = [1, 2, 2, 2, 3, 4, 7]
c
[1, 2, 2, 2, 3, 4, 7]
bisect.bisect(c, 2)
4
c
[1, 2, 2, 2, 3, 4, 7]
bisect.bisect(c, 5)
6
bisect.insort(c, 6)
bisect.insort(c, 100)
c
[1, 2, 2, 2, 3, 4, 6, 7, 100]
seq = [7, 2, 3, 7, 6, 5, 1, 0]
seq
[7, 2, 3, 7, 6, 5, 1, 0]
seq[1: 5]
[2, 3, 7, 6]
seq[3: 4] = [6, 3]
seq
[7, 2, 3, 6, 3, 6, 5, 1, 0]
seq[:5]
[7, 2, 3, 6, 3]
seq[3:]
[6, 3, 6, 5, 1, 0]
seq[-4:]
[6, 5, 1, 0]
seq[::2]
[7, 3, 3, 5, 0]
seq[::-1]
[0, 1, 5, 6, 3, 6, 3, 2, 7]
some_list = ['foo', 'bar', 'baz']
for i, value in enumerate(some_list):
print i, value
0 foo 1 bar 2 baz
mapping = dict((v, i) for i, v in enumerate(some_list))
mapping
{'bar': 1, 'baz': 2, 'foo': 0}
seq
[7, 2, 3, 6, 3, 6, 5, 1, 0]
sorted(seq)
[0, 1, 2, 3, 3, 5, 6, 6, 7]
seq.sort()
seq
[0, 1, 2, 3, 3, 5, 6, 6, 7]
sorted('horse race')
[' ', 'a', 'c', 'e', 'e', 'h', 'o', 'r', 'r', 's']
sorted(set('This is just sone string'))
[' ', 'T', 'e', 'g', 'h', 'i', 'j', 'n', 'o', 'r', 's', 't', 'u']
seq1 = ['foo', 'bar', 'baz']
seq2 = ['one', 'two', 'three']
zip(seq1, seq2)
[('foo', 'one'), ('bar', 'two'), ('baz', 'three')]
seq3 = [False, True]
zip(seq1, seq2, seq3)
[('foo', 'one', False), ('bar', 'two', True)]
for i, (v1, v2) in enumerate(zip(seq1, seq2)):
print i, (v1, v2)
0 ('foo', 'one') 1 ('bar', 'two') 2 ('baz', 'three')
pitchers = [('Nolan', 'Ryan'), ('Roger', 'Clemens'), ('Schiling', 'Curt')]
first_name, last_name = zip(*pitchers)
first_name
('Nolan', 'Roger', 'Schiling')
last_name
('Ryan', 'Clemens', 'Curt')
range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
reversed(range(10))
<listreverseiterator at 0x7fda8c447090>
list(reversed(range(10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
empty_dict = {}
a = {'a': 'some_value', 'b': [1, 2, 3, 4]}
a
{'a': 'some_value', 'b': [1, 2, 3, 4]}
a[7] = 'an integer'
a
{7: 'an integer', 'a': 'some_value', 'b': [1, 2, 3, 4]}
a['a']
'some_value'
'b' in a
True
a[5] = 'some_value'
a
{5: 'some_value', 7: 'an integer', 'a': 'some_value', 'b': [1, 2, 3, 4]}
del a[5]
a
{7: 'an integer', 'a': 'some_value', 'b': [1, 2, 3, 4]}
a.pop(7)
'an integer'
a
{'a': 'some_value', 'b': [1, 2, 3, 4]}
a.keys()
['a', 'b']
a.values()
['some_value', [1, 2, 3, 4]]
a.update({'b': 'foo', 'c': 12})
a
{'a': 'some_value', 'b': 'foo', 'c': 12}
mapping = dict(zip(range(5), list(reversed(range(5)))))
mapping
{0: 4, 1: 3, 2: 2, 3: 1, 4: 0}
words = ['apple', 'bat', 'bar', 'atom', 'book']
by_letters = {}
for word in words:
letter = word[0]
print letter
a b b a b
for word in words:
letter = word[0]
if letter not in by_letters:
by_letters[letter] = [word]
else:
by_letters[letter].append(word)
by_letters
{'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']}
hash('string')
-9167918882415130555
hash((1, 2, 3))
2528502973977326415
hash((1, 2, [3, 4]))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-151-94f25bbf31b2> in <module>() ----> 1 hash((1, 2, [3, 4])) TypeError: unhashable type: 'list'
set([1, 2, 3, 4, 5, 6])
{1, 2, 3, 4, 5, 6}
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
a|b
{1, 2, 3, 4, 5, 6, 7, 8}
a&b
{4, 5}
a - b
{1, 2, 3}
a ^ b
{1, 2, 3, 6, 7, 8}
{1, 2, 3}.issubset(a)
True
a.issuperset({1, 2, 3})
True
a |= b
a
{1, 2, 3, 4, 5, 6, 7, 8}
a |= {'apple'}
a
{1, 2, 3, 4, 5, 6, 7, 8, 'apple'}
strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
[x.upper() for x in strings if len(x)>2]
['BAT', 'CAR', 'DOVE', 'PYTHON']
unique_length = {len(x) for x in strings}
unique_length
{1, 2, 3, 4, 6}
loc_mapping = {val: index for index, val in enumerate(strings)}
loc_mapping
{'a': 0, 'as': 1, 'bat': 2, 'car': 3, 'dove': 4, 'python': 5}
loc_mapping = dict((index, val) for val, index in enumerate(strings))
loc_mapping
{'a': 0, 'as': 1, 'bat': 2, 'car': 3, 'dove': 4, 'python': 5}
all_data = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Susie', 'Casey', 'Jill', 'Ana', 'Eva', 'Jennifer', 'Stephanie']]
name_of_interest = []
for names in all_data:
enough_us = [name for name in names if name.count('e') >= 2]
name_of_interest.extend(enough_us)
name_of_interest
['Jefferson', 'Wesley', 'Steven', 'Jennifer', 'Stephanie']
result = [name for name in names for names in all_data if name.count('e') >= 2]
result
['Jennifer', 'Jennifer', 'Stephanie', 'Stephanie']
some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
flattended = [x for tup in some_tuples for x in tup]
flattended
[1, 2, 3, 4, 5, 6, 7, 8, 9]
fla_2 = [[x for x in tup] for tup in some_tuples]
fla_2
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def my_function(x, y, z=1.5):
if z>1:
return z * (x + y)
else:
return z / (x + y)
my_function(3, 4, z = 0.7)
0.09999999999999999
my_function(3.14, 7, 3.5)
35.49
def func():
a = []
for i in range(5):
a.append(i)
a = []
def func():
for i in range(5):
a.append(i)
a = None
def bind_a_value():
global a
a = []
bind_a_variable()
def outer_function(x, y, z):
def inner_function(a, b, c):
pass
pass
def f():
a = 5
b = 6
c = 7
return a, b, c
a, b, c = f()
def f():
a = 5
b = 6
c = 7
return {'a': a, 'b': b, 'c': c}
states = ['Alabama', 'Georgia!', 'Georgia', 'georgia', 'FLOrida',
'south carolina##', 'West viginia?']
import re
def clean_strings(strings):
result = []
for value in strings:
value = value.strip()
value = re.sub('[!#?]', '', value)
value = value.title()
result.append(value)
return result
clean_strings(states)
['Alabama', 'Georgia', 'Georgia', 'Georgia', 'Florida', 'South Carolina', 'West Viginia']
def remove_punctuation(value):
return re.sub('[!#?]', '', value)
clean_ops = [str.strip, remove_punctuation, str.title]
def clean_strings(strings, ops):
result = []
for value in strings:
for function in clean_ops:
value = function(value)
result.append(value)
return result
clean_strings(states, clean_ops)
['Alabama', 'Georgia', 'Georgia', 'Georgia', 'Florida', 'South Carolina', 'West Viginia']
map(remove_punctuation, states)
['Alabama', 'Georgia', 'Georgia', 'georgia', 'FLOrida', 'south carolina', 'West viginia']
def short_func(x):
return x*2
equal_anno = lambda x: x*2
def apply_to_list(some_list, f):
return [f(x) for x in some_list]
ints = [4, 1, 0, 5, 7]
apply_to_list(ints, lambda x: x*2)
[8, 2, 0, 10, 14]
strings = ['foo', 'bar', 'card', 'aaaa', 'abab']
strings.sort(key = lambda x: len(set(list(strings))))
strings.sort(key = lambda x: len(set(strings)))
def make_closure(a):
def closure():
print 'I know the secret: %d' %a
return closure
closure = make_closure(5)
closure
<function __main__.closure>
print closure
<function closure at 0x7faae033a320>
make_closure(5)
<function __main__.closure>
def make_watcher():
have_seen = {}
def has_been_seen(x):
if x in have_seen:
return True
else:
have_seen[x] = True
return False
return has_been_seen
watcher = make_watcher()
vals = [5, 6, 1, 5, 6, 3, 5]
[watcher(x) for x in vals]
[False, False, False, True, True, False, True]
def make_counter():
count = [0]
def counter():
count[0] += 1
return count[0]
return counter
counter = make_counter()
def format_and_pad(template, space):
def formatter(x):
return (template % x).rjust(space)
return formatter
fmt = format_and_pad('%.4f', 15)
fmt(1.756)
' 1.7560'
def say_hello_then_call_f(f, *args, **kwargs):
print 'args is ', args
print 'kwargs is ', kwargs
print 'Hello, Now I\'m going to call %s.' %f
return f(*args, **kwargs)
def g(x, y, z = 1):
return (x + y)/z
say_hello_then_call_f(g, 5, 7, z = 7.)
args is (5, 7) kwargs is {'z': 7.0} Hello, Now I'm going to call <function g at 0x7faae033aa28>.
1.7142857142857142
def add_numbers(x, y):
return x + y
add_five = lambda y: add_numbers(5, y)
add_five(10)
15
from functools import partial
add_six = partial(add_numbers, 6)
add_six(10)
16
import pandas
ma60 = lambda x: pandas.rolling_mean(x, 60)
data.apply(ma60)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-66-e0cfd4b57de2> in <module>() 1 ma60 = lambda x: pandas.rolling_mean(x, 60) ----> 2 data.apply(ma60) NameError: name 'data' is not defined
some_dict = {'a': 1, 'b': 2, 'c': 3}
for key in some_dict:
print key
a c b
dict_iterator = iter(some_dict)
dict_iterator
<dictionary-keyiterator at 0x7faac204fd60>
list(dict_iterator)
['a', 'c', 'b']
def squares(n = 10):
for i in xrange(1, n + 1):
print 'Generating squares from 1 to %d' %(i**2)
yield i**2
gen = squares()
print gen
<generator object squares at 0x7faac204eaa0>
gen
<generator object squares at 0x7faac204eaa0>
for x in gen:
print x
Generating squares from 1 to 1 1 Generating squares from 1 to 4 4 Generating squares from 1 to 9 9 Generating squares from 1 to 16 16 Generating squares from 1 to 25 25 Generating squares from 1 to 36 36 Generating squares from 1 to 49 49 Generating squares from 1 to 64 64 Generating squares from 1 to 81 81 Generating squares from 1 to 100 100
def make_change(amount, coins = [1, 5, 10, 25], hand = None):
hand = [] if hand is None else hand
if amount == 0:
yield hand
for coin in coins:
if coin > amount or (len(hand) > 0 and hand[-1] < coin):
continue
for result in make_change(amount - coin, coins = coins, hand = hand + [coin]):
yield result
for way in make_change(100, coins=[10, 25, 50]):
print way
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10] [25, 25, 10, 10, 10, 10, 10] [25, 25, 25, 25] [50, 10, 10, 10, 10, 10] [50, 25, 25] [50, 50]
len(list(make_change(100)))
242
gen = (x**2 for x in xrange(100))
gen
<generator object <genexpr> at 0x7faac2078690>
def _make_gen():
for x in xrange(100):
yield x**2
gen = _make_gen()
sum(gen)
328350
sum(x**2 for x in xrange(100))
328350
dict((i, i**2) for i in xrange(5))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
import itertools
first_letter = lambda x: x[0]
names = ['Alan', 'Adam', 'Wes', 'Will', 'Albert', 'Steven']
for letter, name in itertools.groupby(names, first_letter):
print letter, list(name)
A ['Alan', 'Adam'] W ['Wes', 'Will'] A ['Albert'] S ['Steven']
path = 'ch13/segismundo.txt'
f = open(path)
lines = [x.rstrip() for x in open(path)]
lines
['Sue\xc3\xb1a el rico en su riqueza,', 'que m\xc3\xa1s cuidados le ofrece;', '', 'sue\xc3\xb1a el pobre que padece', 'su miseria y su pobreza;', '', 'sue\xc3\xb1a el que a medrar empieza,', 'sue\xc3\xb1a el que afana y pretende,', 'sue\xc3\xb1a el que agravia y ofende,', '', 'y en el mundo, en conclusi\xc3\xb3n,', 'todos sue\xc3\xb1an lo que son,', 'aunque ninguno lo entiende.', '']
with open('tem.txt', 'w') as handle:
handle.writelines(x for x in open(path) if len(x) > 1)
open('tem.txt').readlines()
['Sue\xc3\xb1a el rico en su riqueza,\n', 'que m\xc3\xa1s cuidados le ofrece;\n', 'sue\xc3\xb1a el pobre que padece\n', 'su miseria y su pobreza;\n', 'sue\xc3\xb1a el que a medrar empieza,\n', 'sue\xc3\xb1a el que afana y pretende,\n', 'sue\xc3\xb1a el que agravia y ofende,\n', 'y en el mundo, en conclusi\xc3\xb3n,\n', 'todos sue\xc3\xb1an lo que son,\n', 'aunque ninguno lo entiende.\n']