Introduction to Python

Sourav Nandi, 27/07/2020

References

1) Data School By Kevin Markham (YouTube)

2) Sebastian Raschka : Python Machine Learning (Book)

3) 'Think Python' by Allen B. Downey (Book)

4) The Python Tutorial

In [ ]:
 
In [1]:
# Python and OOP (from programiz.com)

Image

In [2]:
#playing with Markdown

This is a level 1 heading

This is a level 2 heading

This is some plain text that forms a paragraph. Add emphasis via bold and bold, or italic and italic. Paragraphs must be separated by an empty line.

  • Sometimes we want to include lists.
  • Which can be indented.
In [ ]:
 

1. Imports

In [3]:
# 'generic import' of math module
import math
math.sqrt(25)
Out[3]:
5.0
In [4]:
# import a function
from math import sqrt
sqrt(25)    # no longer have to reference the module
Out[4]:
5.0
In [5]:
# import multiple functions at once
from math import cos, floor
In [6]:
# import all functions in a module (generally discouraged)
from csv import *
In [7]:
# define an alias
import datetime as dt
In [8]:
# show all functions in math module
print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

2. Data Types

Determine the type of an object:

In [9]:
type(2)
Out[9]:
int
In [10]:
type(2.0)
Out[10]:
float
In [11]:
type('two')
Out[11]:
str
In [12]:
type(True)
Out[12]:
bool
In [13]:
type(None)
Out[13]:
NoneType

Check if an object is of a given type:

In [14]:
isinstance(2.0, int)
Out[14]:
False
In [15]:
isinstance(2.0, (int, float))
Out[15]:
True

Convert an object to a given type:

In [16]:
float(2)
Out[16]:
2.0
In [17]:
int(2.9)
Out[17]:
2
In [18]:
str(2.9)
Out[18]:
'2.9'

Zero, None, and empty containers are converted to False:

In [19]:
bool(0)
Out[19]:
False
In [20]:
bool(None)
Out[20]:
False
In [21]:
bool('a')
Out[21]:
True
In [22]:
bool(7)
Out[22]:
True
In [23]:
bool('')    # empty string
Out[23]:
False
In [24]:
bool([])    # empty list
Out[24]:
False
In [25]:
bool({})    # empty dictionary
Out[25]:
False

Non-empty containers and non-zeros are converted to True:

In [26]:
bool(2)
Out[26]:
True
In [27]:
bool('two')
Out[27]:
True
In [28]:
bool([2])
Out[28]:
True

3. Math

In [29]:
10 + 4
Out[29]:
14
In [30]:
10 - 4
Out[30]:
6
In [31]:
10 * 4
Out[31]:
40
In [32]:
10 ** 4    # exponent
Out[32]:
10000
In [33]:
5 % 4      # modulo - computes the remainder
Out[33]:
1
In [34]:
# Python 2: returns 2 (because both types are 'int')
# Python 3: returns 2.5
10 / 4
Out[34]:
2.5
In [35]:
10 / 4
Out[35]:
2.5

4. Comparisons and Boolean Operations

Assignment statement:

In [36]:
x = 5

Comparisons:

In [37]:
x > 3
Out[37]:
True
In [38]:
x >= 3
Out[38]:
True
In [39]:
x != 3
Out[39]:
True
In [40]:
x == 5
Out[40]:
True

Boolean operations:

In [41]:
5 > 3 and 6 > 3
Out[41]:
True
In [42]:
5 > 3 or 5 < 3
Out[42]:
True
In [43]:
not False
Out[43]:
True
In [44]:
False or True
Out[44]:
True
In [45]:
False and True
Out[45]:
False
In [46]:
False or not False and True     # evaluation order: not, and, or
Out[46]:
True

5. Conditional Statements

In [47]:
x=1
In [48]:
# if statement
if x > 0:
    print('positive')
positive
In [49]:
# if/else statement
if x > 0:
    print('positive')
else:
    print('zero or negative')
positive
In [50]:
# if/elif/else statement
if x > 0:
    print('positive')
elif x == 0:
    print('zero')
else:
    print('negative')
positive
In [51]:
# single-line if statement (sometimes discouraged)
if x > 0: print('positive')
positive
In [52]:
# single-line if/else statement (sometimes discouraged), known as a 'ternary operator'
'positive' if x > 0 else 'zero or negative'
Out[52]:
'positive'

6. Lists

  • List properties: ordered, iterable, mutable, can contain multiple data types
In [53]:
# create an empty list (two ways)
empty_list = []
empty_list = list()
In [54]:
# create a list
simpsons = ['homer', 'marge', 'bart']

Examine a list:

In [55]:
# print element 0
simpsons[0]
Out[55]:
'homer'
In [56]:
len(simpsons)
Out[56]:
3

Modify a list (does not return the list):

In [57]:
# append element to end
simpsons.append('lisa')
simpsons
Out[57]:
['homer', 'marge', 'bart', 'lisa']
In [58]:
# append multiple elements to end
simpsons.extend(['itchy', 'scratchy'])
simpsons
Out[58]:
['homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']
In [59]:
# insert element at index 0 (shifts everything right)
simpsons.insert(0, 'maggie')
simpsons
Out[59]:
['maggie', 'homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']
In [60]:
# search for first instance and remove it
simpsons.remove('bart')
simpsons
Out[60]:
['maggie', 'homer', 'marge', 'lisa', 'itchy', 'scratchy']
In [61]:
# remove element 0 and return it
simpsons.pop(0)
Out[61]:
'maggie'
In [62]:
# remove element 0 (does not return it)
del simpsons[0]
simpsons
Out[62]:
['marge', 'lisa', 'itchy', 'scratchy']
In [63]:
# replace element 0
simpsons[0] = 'krusty'
simpsons
Out[63]:
['krusty', 'lisa', 'itchy', 'scratchy']
In [64]:
# concatenate lists (slower than 'extend' method)
neighbors = simpsons + ['ned', 'rod', 'todd']
neighbors
Out[64]:
['krusty', 'lisa', 'itchy', 'scratchy', 'ned', 'rod', 'todd']

Find elements in a list:

In [65]:
# counts the number of instances
simpsons.count('lisa')
Out[65]:
1
In [66]:
# returns index of first instance
simpsons.index('itchy')
Out[66]:
2

List slicing:

In [67]:
weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']
In [68]:
# element 0
weekdays[0]
Out[68]:
'mon'
In [69]:
# elements 0 (inclusive) to 3 (exclusive)
weekdays[0:3]
Out[69]:
['mon', 'tues', 'wed']
In [70]:
# starting point is implied to be 0
weekdays[:3]
Out[70]:
['mon', 'tues', 'wed']
In [71]:
# elements 3 (inclusive) through the end
weekdays[3:]
Out[71]:
['thurs', 'fri']
In [72]:
# last element
weekdays[-1]
Out[72]:
'fri'
In [73]:
# every 2nd element (step by 2)
weekdays[::2]
Out[73]:
['mon', 'wed', 'fri']
In [74]:
# backwards (step by -1)
weekdays[::-1]
Out[74]:
['fri', 'thurs', 'wed', 'tues', 'mon']
In [75]:
weekdays[::-2]
Out[75]:
['fri', 'wed', 'mon']
In [76]:
# alternative method for returning the list backwards
list(reversed(weekdays))
Out[76]:
['fri', 'thurs', 'wed', 'tues', 'mon']

Sort a list in place (modifies but does not return the list):

In [77]:
simpsons.sort()
simpsons
Out[77]:
['itchy', 'krusty', 'lisa', 'scratchy']
In [78]:
# sort in reverse
simpsons.sort(reverse=True)
simpsons
Out[78]:
['scratchy', 'lisa', 'krusty', 'itchy']
In [79]:
# sort by a key
simpsons.sort(key=len)
simpsons
Out[79]:
['lisa', 'itchy', 'krusty', 'scratchy']

Return a sorted list (does not modify the original list):

In [80]:
sorted(simpsons)
Out[80]:
['itchy', 'krusty', 'lisa', 'scratchy']
In [81]:
sorted(simpsons, reverse=True)
Out[81]:
['scratchy', 'lisa', 'krusty', 'itchy']
In [82]:
sorted(simpsons, key=len)
Out[82]:
['lisa', 'itchy', 'krusty', 'scratchy']

Insert into an already sorted list, and keep it sorted:

In [83]:
num = [10, 20, 40, 50]
from bisect import insort
insort(num, 30)
num
Out[83]:
[10, 20, 30, 40, 50]

Object references and copies:

In [84]:
# create a second reference to the same list
same_num = num
In [85]:
# modifies both 'num' and 'same_num'
same_num[0] = 0
print(num)
print(same_num)
[0, 20, 30, 40, 50]
[0, 20, 30, 40, 50]
In [86]:
# copy a list (two ways)
new_num = num[:]
new_num = list(num)

Examine objects:

In [87]:
num is same_num    # checks whether they are the same object
Out[87]:
True
In [88]:
num is new_num
Out[88]:
False
In [89]:
num == same_num    # checks whether they have the same contents
Out[89]:
True
In [90]:
num == new_num
Out[90]:
True

7. Tuples

  • Tuple properties: ordered, iterable, immutable, can contain multiple data types
  • Like lists, but they don't change size
In [91]:
# create a tuple directly
digits = (0, 1, 'two')
In [92]:
# create a tuple from a list
digits = tuple([0, 1, 'two'])
In [93]:
# trailing comma is required to indicate it's a tuple
zero = (0,)

Examine a tuple:

In [94]:
digits[2]
Out[94]:
'two'
In [95]:
len(digits)
Out[95]:
3
In [96]:
# counts the number of instances of that value
digits.count(0)
Out[96]:
1
In [97]:
# returns the index of the first instance of that value
digits.index(1)
Out[97]:
1

Modify a tuple:

In [98]:
# elements of a tuple cannot be modified (this would throw an error)
# digits[2] = 2
In [99]:
# concatenate tuples
digits = digits + (3, 4)
digits
Out[99]:
(0, 1, 'two', 3, 4)

Other tuple operations:

In [100]:
# create a single tuple with elements repeated (also works with lists)
(3, 4) * 2
Out[100]:
(3, 4, 3, 4)
In [101]:
# sort a list of tuples
tens = [(20, 60), (10, 40), (20, 30)]
sorted(tens)    # sorts by first element in tuple, then second element
Out[101]:
[(10, 40), (20, 30), (20, 60)]
In [102]:
# tuple unpacking
bart = ('male', 10, 'simpson')    # create a tuple
(sex, age, surname) = bart        # assign three values at once
print(sex)
print(age)
print(surname)
male
10
simpson

8. Strings

  • String properties: iterable, immutable
In [103]:
# convert another data type into a string
s = str(42)
s
Out[103]:
'42'
In [104]:
# create a string directly
s = 'I like you'

Examine a string:

In [105]:
s[0]
Out[105]:
'I'
In [106]:
len(s)
Out[106]:
10

String slicing is like list slicing:

In [107]:
s[:6]
Out[107]:
'I like'
In [108]:
s[7:]
Out[108]:
'you'
In [109]:
s[-1]
Out[109]:
'u'

Basic string methods (does not modify the original string):

In [110]:
s.lower()
Out[110]:
'i like you'
In [111]:
s.upper()
Out[111]:
'I LIKE YOU'
In [112]:
s.startswith('I')
Out[112]:
True
In [113]:
s.endswith('you')
Out[113]:
True
In [114]:
# checks whether every character in the string is a digit
s.isdigit()
Out[114]:
False
In [115]:
# returns index of first occurrence, but doesn't support regex
s.find('like')
Out[115]:
2
In [116]:
# returns -1 since not found
s.find('hate')
Out[116]:
-1
In [117]:
# replaces all instances of 'like' with 'love'
s.replace('like', 'love')
Out[117]:
'I love you'

Split a string:

In [118]:
# split a string into a list of substrings separated by a delimiter
s.split(' ')
Out[118]:
['I', 'like', 'you']
In [119]:
# equivalent (since space is the default delimiter)
s.split()
Out[119]:
['I', 'like', 'you']
In [120]:
s2 = 'a, an, the'
s2.split(',')
Out[120]:
['a', ' an', ' the']

Join or concatenate strings:

In [121]:
# join a list of strings into one string using a delimiter
stooges = ['larry', 'curly', 'moe']
' '.join(stooges)
Out[121]:
'larry curly moe'
In [122]:
# concatenate strings
s3 = 'The meaning of life is'
s4 = '42'
s3 + ' ' + s4
Out[122]:
'The meaning of life is 42'

Remove whitespace from the start and end of a string:

In [123]:
s5 = '  ham and cheese  '
s5.strip()
Out[123]:
'ham and cheese'

String substitutions:

In [124]:
# old way
'raining %s and %s' % ('cats', 'dogs')
Out[124]:
'raining cats and dogs'
In [125]:
# new way
'raining {} and {}'.format('cats', 'dogs')
Out[125]:
'raining cats and dogs'
In [126]:
# new way (using named arguments)
'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs')
Out[126]:
'raining cats and dogs'

String formatting (more examples):

In [127]:
# use 2 decimal places
'pi is {:.2f}'.format(3.14159)
Out[127]:
'pi is 3.14'

Normal strings versus raw strings:

In [128]:
# normal strings allow for escaped characters
print('first line\nsecond line')
first line
second line
In [129]:
# raw strings treat backslashes as literal characters
print(r'first line\nfirst line')
first line\nfirst line

9. Dictionaries

  • Dictionary properties: unordered, iterable, mutable, can contain multiple data types
  • Made of key-value pairs
  • Keys must be unique, and can be strings, numbers, or tuples
  • Values can be any type
In [130]:
# create an empty dictionary (two ways)
empty_dict = {}
empty_dict = dict()
In [131]:
# create a dictionary (two ways)
family = {'dad':'homer', 'mom':'marge', 'size':6}
family = dict(dad='homer', mom='marge', size=6)
family
Out[131]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}
In [132]:
# convert a list of tuples into a dictionary
list_of_tuples = [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]
family = dict(list_of_tuples)
family
Out[132]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}

Examine a dictionary:

In [133]:
# pass a key to return its value
family['dad']
Out[133]:
'homer'
In [134]:
# return the number of key-value pairs
len(family)
Out[134]:
3
In [135]:
# check if key exists in dictionary
'mom' in family
Out[135]:
True
In [136]:
# dictionary values are not checked
'marge' in family
Out[136]:
False
In [137]:
# returns a list of keys (Python 2) or an iterable view (Python 3)
family.keys()
Out[137]:
dict_keys(['dad', 'mom', 'size'])
In [138]:
# returns a list of values (Python 2) or an iterable view (Python 3)
family.values()
Out[138]:
dict_values(['homer', 'marge', 6])
In [139]:
# returns a list of key-value pairs (Python 2) or an iterable view (Python 3)
family.items()
Out[139]:
dict_items([('dad', 'homer'), ('mom', 'marge'), ('size', 6)])

Modify a dictionary (does not return the dictionary):

In [140]:
# add a new entry
family['cat'] = 'snowball'
family
Out[140]:
{'dad': 'homer', 'mom': 'marge', 'size': 6, 'cat': 'snowball'}
In [141]:
# edit an existing entry
family['cat'] = 'snowball ii'
family
Out[141]:
{'dad': 'homer', 'mom': 'marge', 'size': 6, 'cat': 'snowball ii'}
In [142]:
# delete an entry
del family['cat']
family
Out[142]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}
In [143]:
# dictionary value can be a list
family['kids'] = ['bart', 'lisa']
family
Out[143]:
{'dad': 'homer', 'mom': 'marge', 'size': 6, 'kids': ['bart', 'lisa']}
In [144]:
# remove an entry and return the value
family.pop('dad')
Out[144]:
'homer'
In [145]:
# add multiple entries
family.update({'baby':'maggie', 'grandpa':'abe'})
family
Out[145]:
{'mom': 'marge',
 'size': 6,
 'kids': ['bart', 'lisa'],
 'baby': 'maggie',
 'grandpa': 'abe'}

Access values more safely with get:

In [146]:
family['mom']
Out[146]:
'marge'
In [147]:
# equivalent to a dictionary lookup
family.get('mom')
Out[147]:
'marge'
In [148]:
# this would throw an error since the key does not exist
# family['grandma']
In [149]:
# return None if not found
family.get('grandma')
In [150]:
# provide a default return value if not found
family.get('grandma', 'not found')
Out[150]:
'not found'

Access a list element within a dictionary:

In [151]:
family['kids'][0]
Out[151]:
'bart'
In [152]:
family['kids'].remove('lisa')
family
Out[152]:
{'mom': 'marge',
 'size': 6,
 'kids': ['bart'],
 'baby': 'maggie',
 'grandpa': 'abe'}

String substitution using a dictionary:

In [153]:
'youngest child is %(baby)s' % family
Out[153]:
'youngest child is maggie'

10. Sets

  • Set properties: unordered, iterable, mutable, can contain multiple data types
  • Made of unique elements (strings, numbers, or tuples)
  • Like dictionaries, but with keys only (no values)
In [154]:
# create an empty set
empty_set = set()
In [155]:
# create a set directly
languages = {'python', 'r', 'java'}
In [156]:
# create a set from a list
snakes = set(['cobra', 'viper', 'python'])

Examine a set:

In [157]:
len(languages)
Out[157]:
3
In [158]:
'python' in languages
Out[158]:
True

Set operations:

In [159]:
# intersection
languages & snakes
Out[159]:
{'python'}
In [160]:
# union
languages | snakes
Out[160]:
{'cobra', 'java', 'python', 'r', 'viper'}
In [161]:
# set difference
languages - snakes
Out[161]:
{'java', 'r'}
In [162]:
# set difference
snakes - languages
Out[162]:
{'cobra', 'viper'}

Modify a set (does not return the set):

In [163]:
# add a new element
languages.add('sql')
languages
Out[163]:
{'java', 'python', 'r', 'sql'}
In [164]:
# try to add an existing element (ignored, no error)
languages.add('r')
languages
Out[164]:
{'java', 'python', 'r', 'sql'}
In [165]:
# remove an element
languages.remove('java')
languages
Out[165]:
{'python', 'r', 'sql'}
In [166]:
# try to remove a non-existing element (this would throw an error)
# languages.remove('c')
In [167]:
# remove an element if present, but ignored otherwise
languages.discard('c')
languages
Out[167]:
{'python', 'r', 'sql'}
In [168]:
# remove and return an arbitrary element
languages.pop()
Out[168]:
'sql'
In [169]:
# remove all elements
languages.clear()
languages
Out[169]:
set()
In [170]:
# add multiple elements (can also pass a set)
languages.update(['go', 'spark'])
languages
Out[170]:
{'go', 'spark'}

Get a sorted list of unique elements from a list:

In [171]:
sorted(set([9, 0, 2, 1, 0]))
Out[171]:
[0, 1, 2, 9]

11. Defining Functions

Define a function with no arguments and no return values:

In [172]:
def print_text():
    print('this is text')
In [173]:
# call the function
print_text()
this is text

Define a function with one argument and no return values:

In [174]:
def print_this(x):
    print(x)
In [175]:
# call the function
print_this(3)
3
In [176]:
# prints 3, but doesn't assign 3 to n because the function has no return statement
n = print_this(3)
3

Define a function with one argument and one return value:

In [177]:
def square_this(x):
    return x**2
In [178]:
# include an optional docstring to describe the effect of a function
def square_this(x):
    """Return the square of a number."""
    return x**2
In [179]:
# call the function
square_this(3)
Out[179]:
9
In [180]:
# assigns 9 to var, but does not print 9
var = square_this(3)

Define a function with two 'positional arguments' (no default values) and one 'keyword argument' (has a default value):

In [181]:
def calc(a, b, op='add'):
    if op == 'add':
        return a + b
    elif op == 'sub':
        return a - b
    else:
        print('valid operations are add and sub')
In [182]:
# call the function
calc(10, 4, op='add')
Out[182]:
14
In [183]:
# unnamed arguments are inferred by position
calc(10, 4, 'add')
Out[183]:
14
In [184]:
# default for 'op' is 'add'
calc(10, 4)
Out[184]:
14
In [185]:
calc(10, 4, 'sub')
Out[185]:
6
In [186]:
calc(10, 4, 'div')
valid operations are add and sub

Use pass as a placeholder if you haven't written the function body:

In [187]:
def stub():
    pass

Return two values from a single function:

In [188]:
def min_max(nums):
    return min(nums), max(nums)
In [189]:
# return values can be assigned to a single variable as a tuple
nums = [1, 2, 3]
min_max_num = min_max(nums)
min_max_num
Out[189]:
(1, 3)
In [190]:
# return values can be assigned into multiple variables using tuple unpacking
min_num, max_num = min_max(nums)
print(min_num)
print(max_num)
1
3

12. Anonymous (Lambda) Functions

  • Primarily used to temporarily define a function for use by another function
In [191]:
# define a function the "usual" way
def squared(x):
    return x**2
In [192]:
# define an identical function using lambda
squared = lambda x: x**2

Sort a list of strings by the last letter:

In [193]:
# without using lambda
simpsons = ['homer', 'marge', 'bart']
def last_letter(word):
    return word[-1]
sorted(simpsons, key=last_letter)
Out[193]:
['marge', 'homer', 'bart']
In [194]:
# using lambda
sorted(simpsons, key=lambda word: word[-1])
Out[194]:
['marge', 'homer', 'bart']

13. For Loops and While Loops

range returns a list of integers (Python 2) or a sequence (Python 3):

In [195]:
# includes the start value but excludes the stop value
range(0, 3)
Out[195]:
range(0, 3)
In [196]:
# default start value is 0
range(3)
Out[196]:
range(0, 3)
In [197]:
# third argument is the step value
range(0, 5, 2)
Out[197]:
range(0, 5, 2)

for loops:

In [198]:
# not the recommended style
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
    print(fruits[i].upper())
APPLE
BANANA
CHERRY
In [199]:
# recommended style
for fruit in fruits:
    print(fruit.upper())
APPLE
BANANA
CHERRY
In [200]:
# iterate through two things at once (using tuple unpacking)
family = {'dad':'homer', 'mom':'marge', 'size':6}
for key, value in family.items():
    print(key, value)
dad homer
mom marge
size 6
In [201]:
# use enumerate if you need to access the index value within the loop
for index, fruit in enumerate(fruits):
    print(index, fruit)
0 apple
1 banana
2 cherry

for/else loop:

In [202]:
for fruit in fruits:
    if fruit == 'banana':
        print('Found the banana!')
        break    # exit the loop and skip the 'else' block
else:
    # this block executes ONLY if the for loop completes without hitting 'break'
    print("Can't find the banana")
Found the banana!

while loop:

In [203]:
count = 0
while count < 5:
    print('This will print 5 times')
    count += 1    # equivalent to 'count = count + 1'
This will print 5 times
This will print 5 times
This will print 5 times
This will print 5 times
This will print 5 times

14. Comprehensions

List comprehension:

In [204]:
# for loop to create a list of cubes
nums = [1, 2, 3, 4, 5]
cubes = []
for num in nums:
    cubes.append(num**3)
cubes
Out[204]:
[1, 8, 27, 64, 125]
In [205]:
# equivalent list comprehension
cubes = [num**3 for num in nums]
cubes
Out[205]:
[1, 8, 27, 64, 125]
In [206]:
# for loop to create a list of cubes of even numbers
cubes_of_even = []
for num in nums:
    if num % 2 == 0:
        cubes_of_even.append(num**3)
cubes_of_even
Out[206]:
[8, 64]
In [207]:
# equivalent list comprehension
# syntax: [expression for variable in iterable if condition]
cubes_of_even = [num**3 for num in nums if num % 2 == 0]
cubes_of_even
Out[207]:
[8, 64]
In [208]:
# for loop to cube even numbers and square odd numbers
cubes_and_squares = []
for num in nums:
    if num % 2 == 0:
        cubes_and_squares.append(num**3)
    else:
        cubes_and_squares.append(num**2)
cubes_and_squares
Out[208]:
[1, 8, 9, 64, 25]
In [209]:
# equivalent list comprehension (using a ternary expression)
# syntax: [true_condition if condition else false_condition for variable in iterable]
cubes_and_squares = [num**3 if num % 2 == 0 else num**2 for num in nums]
cubes_and_squares
Out[209]:
[1, 8, 9, 64, 25]
In [210]:
# for loop to flatten a 2d-matrix
matrix = [[1, 2], [3, 4]]
items = []
for row in matrix:
    for item in row:
        items.append(item)
items
Out[210]:
[1, 2, 3, 4]
In [211]:
# equivalent list comprehension
items = [item for row in matrix
              for item in row]
items
Out[211]:
[1, 2, 3, 4]

Set comprehension:

In [212]:
fruits = ['apple', 'banana', 'cherry']
unique_lengths = {len(fruit) for fruit in fruits}
unique_lengths
Out[212]:
{5, 6}

Dictionary comprehension:

In [213]:
fruit_lengths = {fruit:len(fruit) for fruit in fruits}
fruit_lengths
Out[213]:
{'apple': 5, 'banana': 6, 'cherry': 6}
In [214]:
fruit_indices = {fruit:index for index, fruit in enumerate(fruits)}
fruit_indices
Out[214]:
{'apple': 0, 'banana': 1, 'cherry': 2}
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: