| Data | Mutable? | Ordered Items? | Unique Items? | Item Access |
|---|---|---|---|---|
| List | Yes | Yes | No | Index |
| Tuple | No | Yes | No | Index |
| Dictionary | Yes | No | Yes | Key |
| Set | Yes | No | Yes | None |
| String | No | Yes | No | Index |
truth_statement if condition else false_statement
List comprehension is a concise way of creating a list. The syntax is
[expression for item in list if condition]
Notice [ and ] around the statement indicating that a list will be returned. This is equivalent to
for item in list:
if condition:
expression
The if-condition is optional.
{item for item in set if condition}
tuple(item for item in tuple if condition)
{key:value for (key, value) in list-of-tuples if condition},
where list of tuples could be obtained by zip(iterable1, iterable2) (iterables are lists, tuples, sets) or dict.items().
'{0} {1}'.format(arg1, arg2),
where args can be any of the 8 data structures listed above.
In [1]:
print '{} == {} is {}'.format(1, [1], False)
print 'My name is {1}, {0} {1}!'.format('James', 'Bond')
Lambda() is small, anonymous function (functions without names). They are disposable functions, i.e. they are used only where they are created.
Map() applies a function to each item in a sequence (list, tuple, set). The syntax is
map(function, sequence-of-items).
Great use case for lambda().
Filter() returns a sequence of items (list, tuple, set) that satisfy a given condition. The syntax is
filter(condition, sequence-of-items).
Great use case for lambda(). Note: Comprehensions could be used in place of Map() & Filter().
Reduce() continually applies a function to a sequence of items (list, tuple, set). It returns a single value. The syntax is
reduce(function, sequence-of-items).
Great use case for lambda().
In [2]:
celsius = [39.2, 36.5, 37.3, 37.8]
fahrenheit = map(lambda x: (float(9)/5)*x + 32, celsius)
fahrenheit
Out[2]:
In [3]:
fib = [0,1,1,2,3,5,8,13,21,34,55]
filter(lambda x: x % 2 == 0, fib)
Out[3]:
In [4]:
f = lambda x,y: x if (x > y) else y
reduce(f, [47,11,42,102,13])
Out[4]:
With an iterable, such as list or tuple:
args = (1, 2, 3)
f(*args) -> f(1, 2, 3)
print range(*(0, 5))
print range(*[0, 5, 2]) # range(start, end, step)
With a mapping, such as dict:
kwargs = {'a':1, 'b':2, 'c':3}
f(**kwargs) -> f(a=1, b=2, c=3)
dic = {'a':1, 'b':2}
def myFunc(a=0, b=0, c=0):
print(a, b, c)
myFunc(**dic)
In [5]:
a, b = [1, 2]
c, d = (3, 4)
e, f = {5, 6}
print a, b, c, d, e, f
[] creates empty list[1, 2], [3, 4] creates nested listlist[start:stop:step] sliceslist1 + list2 concatenatesitem in list checks membership.append(item) appends item to the end of the list.remove(item) removes 1st value from list.insert(index, item) inserts item to specified index.pop(index) inverse of insert.sort() sorts.reverse() reverses() creates empty tuple. 1,2 creates tuple.(1, 2), (3, 4) creates nested tupletup[start:stop:step] slicestup1 + tup2 concatenatesitem in tup checks membershipset() creates empty set{1}, {2} creates nested set1 in {1, 2} checks membershipset1.issubset(set2) $A \subseteq B$set1.issuperset(set2) $B \subseteq A$set1 == set2set1 | set2 $A \cup B$set1 & set2 $ A \cap B$set1 - set2 $A-B$: elements in set1, but NOT in set2set1 ^ set2 $(A \cap B)^c$: symmetric difference (xor) .add(item) appends item to set.remove(item) removes item to setset1.update(set2) appends set2 items to set1{} creates empty dictionary{'a':1}, {'b':2} creates nested dictionarydict(zip(keys, values)) creates dict from iterable (list, tuple, set) keys and values. zip creates a list of $(k,v)$ tuples.d[key] prints values for keyd[key] = value inserts/updates value for key.keys() produces keys list.values() produces values listkey in d checks if key existsdel d[key] deletes the key-value pair from dictionaryd1.update(d2) appends d2 key-value pairs to d1'' or "" or ''' ''' creates empty string. Triple quotes allow line breaks.string[start:stop:step] slicesstr1 + str2 concatenates's' in 'string' checks membership.lower() converts to lowercase.upper() converts to uppercasestr.split(delimiter=" ") splits str by delimiter, default spaceseparator.join(iterable) concatenates strings in iterable (list, tuple, string, dictionary, set) with separator stringstr.replace(old_string, new_string) replaces all occurrences of old_string with new_stringstr.strip(string) removes string from the beginning and the end of str. str.lstrip(string) removes string only from the beginning. str.rstrip(string) removes string only from the end.str.startswith(string) and str.endswith(string) checks if str starts with or ends with stringstr.swapcase() swap uppercase with lowercase and vice-versastr.count(substring) counts how many times substring occurs in str
In [6]:
li = range(1, 4)
d = 3
[[l*i for l in li] for i in range(1, d+1)]
Out[6]:
Example: If list[2]=2, include. If list[3]=2, exclude
In [7]:
li = [1,3,5,8,10,13,18,36,78]
[x for x in li[::2] if x%2 == 0]
Out[7]:
Example: If d=2 and list=[1,2,3,4,5], then 2-left rotation is [3,4,5,1,2]
In [8]:
li = range(1, 6)
d = 2
li[d:] + li[:d]
Out[8]:
In [9]:
x = 2
y = 3
d = 4
list1 = range(0, x+1)
list2 = range(0, y+1)
[(i,j) for i in list1 for j in list2 if i+j != d]
Out[9]:
Example: Convert "divya nair" to "Divya Nair"
In [10]:
"divya nair".title()
#"divya nair".capitalize()
Out[10]:
In [11]:
name = "divya nair"
li = name.split(" ")
li = [li[i].capitalize() for i in range(0, len(li))]
" ".join(li)
Out[11]:
In [12]:
s = "ABCDEFGHIJKLIMNOQRSTUVWXYZ"
d = 4
i = 0
while (i < len(s)):
print s[i:i+d]
i = i+d
In [13]:
string = "divya nair"
vowels = ["a", "e", "i", "o", "u"]
[char for char in string if char in vowels]
Out[13]:
In [14]:
n = 3
reduce(lambda x,y: x*y, range(1, n+1))
Out[14]:
In [15]:
import random
size = 3
# Generate 3 random numbers between [1, 10]
numList = [random.randint(1,10) for i in range(0, size)]
print numList
"The sum is {}".format(reduce(lambda x,y: x+y, numList))
Out[15]:
In [16]:
# Shuffle item position in numList
random.shuffle(numList)
numList
Out[16]:
In [17]:
# Randomly sample 2 items from numList
print random.sample(numList, 2)
In [18]:
n = 6
d = 3
a = [1, 3, 2, 6, 1, 2]
sums = [(a[i] + a[j], i, j) for i in range(0, len(a)) for j in range(0, len(a))]
[(s[1], s[2]) for s in sums if s[0]%d==0]
Out[18]:
In [19]:
fib = [0,1]
n = 6
for i in range(0, n):
fib.append(fib[i] + fib[i+1])
fib
Out[19]:
Example: $2.12 = (25c, 8), (10c, 1), (2c, 2)
In [20]:
amount = 0.50
dollar, cent = str(amount).split(".")
cent = cent+'0' if len(cent)==1 else cent # ternary operation
amount = int(dollar+cent)
deno = [25, 10, 5, 1]
coins = []
for d in deno:
coins.append(amount/d)
amount = amount%d
print '{} quarters, {} dimes, {} nickels, {} pennies'.format(*coins) # unpacking list
In [21]:
row = [1]
print row
d = 4
while (len(row) <= d):
row = [1] + [row[i] + row[i+1] for i in range(0, len(row)-1)] + [1]
print row
In [22]:
stops = [[10, 6], [5, 4]]
remaining = [x[0]-x[1] for x in stops]
reduce(lambda x,y: x+y, remaining)
Out[22]:
In [23]:
num = [2, 3, 6, 6, -5]
noRep = list(set(num))
noRep.sort()
noRep.pop(-2)
Out[23]:
In [24]:
length = 2
width = 3
for l in range(0, length):
print '* ' * width
In [25]:
num = [0, 1, 2, -3]
print num
odd = filter(lambda x: x%2 != 0, num)
print odd
reduce(lambda x,y: x+y, odd)
Out[25]: