Python Crash Course

Lists and sets


In [2]:
# Regarding lists in python
my_list = ['a', 'b', 'c', 'd']

In [3]:
print(my_list[0:2])    # grab everything from index 0 uptill index 2 but not including index 2


['a', 'b']

In [4]:
print(my_list[:2])     # grab everything from everythin uptill index 2 but not including index 2


['a', 'b']

In [5]:
print([my_list[2:]])   # grab everything from index 2 uptill everything


[['c', 'd']]

In [7]:
# Nested lists
nested = [1,2,['a','b']]

In [8]:
print(nested[2][0])


a

In [9]:
# Regarding sets
# Sets are the collection on unique items 
s = {1,2,3,5,5,5,5,1,6}
print(s)


{1, 2, 3, 5, 6}

In [10]:
# Or
s = set([1,1,1,6,3,3,8,4])
print(s)


{1, 3, 4, 6, 8}

Comparison operators


In [11]:
1 == 1


Out[11]:
True

In [12]:
1 > 2


Out[12]:
False

In [13]:
1 < 6


Out[13]:
True

In [14]:
3 >= 3


Out[14]:
True

In [16]:
1 == '1'     #important


Out[16]:
False

Logic operators


In [17]:
(1 == 1) and (1 == 2)


Out[17]:
False

In [18]:
(1 == 1) or (1 == 2)


Out[18]:
True

In [19]:
(1 == 1) and not (1 == 2)


Out[19]:
True

if,elif, else Statements


In [20]:
if True:
    print('hello')


hello

In [21]:
if False:
    print('hello')
elif True:
    print('elif is True')


elif is True

In [22]:
if False:
    print('hello')
elif False:
    print('elif is True')
else:
    print('else is True')


else is True

def, lamdba, map and filter


In [23]:
def power_2(num):
    return num ** 2

In [24]:
power_2(4)


Out[24]:
16

In [25]:
seq = [1,2,3,4,5,6,7,8,9]
list(map(lambda num: num ** 2, seq))


Out[25]:
[1, 4, 9, 16, 25, 36, 49, 64, 81]

In [26]:
def is_even(num):
    return num % 2 == 0

list(filter(is_even, seq))


Out[26]:
[2, 4, 6, 8]

In [27]:
list(filter(lambda num: num % 2 == 0, seq))


Out[27]:
[2, 4, 6, 8]

in keyword


In [28]:
lst = [1,2,3]

In [29]:
'x' in [1,2,3]


Out[29]:
False

In [30]:
'x' in ['x','y','z']


Out[30]:
True

In [ ]: