x = 3
print(type(x)) # Prints "<class 'int'>"
print(x) # Prints "3"
print(x + 1) # Addition; prints "4"
print(x - 1) # Subtraction; prints "2"
print(x * 2) # Multiplication; prints "6"
print(x ** 2) # Exponentiation; prints "9"
x += 1
print(x) # Prints "4"
x *= 2
print(x) # Prints "8"
y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"
<class 'int'> 3 4 2 6 9 4 8 <class 'float'> 2.5 3.5 5.0 6.25
x = 'c'
print(type(x))
<class 'str'>
t = True
f = False
print(type(t)) # Prints "<class 'bool'>"
print(t and f) # Logical AND; prints "False"
print(t or f) # Logical OR; prints "True"
print(not t) # Logical NOT; prints "False"
print(t != f) # Logical XOR; prints "True"
<class 'bool'> False True False True
2 == 23
False
hello = 'helloworld' # String literals can use single quotes
world = "world" # or double quotes; it does not matter.
print(hello) # Prints "hello"
print(len(hello)) # String length; prints "5"
hw = hello + ' ' + world # String concatenation
print(hw) # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatting
print(hw12) # prints "hello world 12"
helloworld 10 helloworld world helloworld world 12
s = "hello"
print(s.capitalize()) # Capitalize a string; prints "Hello"
print(s.upper()) # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7)) # Right-justify a string, padding with spaces; prints " hello"
print(s.center(7)) # Center a string, padding with spaces; prints " hello "
print(s.replace('l', '(ell)')) # Replace all instances of one substring with another;
# prints "he(ell)(ell)o"
print(' world '.strip()) # Strip leading and trailing whitespace; prints "world"
Hello HELLO hello hello he(ell)(ell)o world
xs = [3, 1, 2] # Create a list
print(xs, xs[2]) # Prints "[3, 1, 2] 2"
print(xs[-1]) # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo' # Lists can contain elements of different types
print(xs) # Prints "[3, 1, 'foo']"
xs.append('bar') # Add a new element to the end of the list
print(xs) # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop() # Remove and return the last element of the list
print(x, xs) # Prints "bar [3, 1, 'foo']"
[3, 1, 2] 2 2 [3, 1, 'foo'] [3, 1, 'foo', 'bar'] bar [3, 1, 'foo']
xs = [3, 1, 2,5,7]
xs[-len(xs)]
3
xs[3] = 'f'
xs
[3, 1, 2, 'f', 7]
aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009)
print ("Final List : ", aList)
Final List : [123, 'xyz', 'zara', 2009, 'abc']
nums = list(range(5)) # range is a built-in function that creates a list of integers
print(nums) # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:]) # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[:-1]) # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
print(nums)
[0, 1, 2, 3, 4] [2, 3] [2, 3, 4] [0, 1] [0, 1, 2, 3, 4] [0, 1, 2, 3] [0, 1, 8, 9, 4]
nums = list(range(6))
nums
[0, 1, 2, 3, 4, 5]
nums[:2], nums[2:4], nums[4:]
([0, 1], [2, 3], [4, 5])
animals = ['cat', 'dog', 'monkey']
for animal in animals: print(animal)
cat dog monkey
animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print(idx, animal)
0 cat 1 dog 2 monkey
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
squares.append(x ** 2)
print(squares) # Prints [0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
Fast and pythonic way of doing operations oin lists
nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares) # Prints [0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
nums = [0, 1, 2, 3, 4]
odd_squares = [x ** 2 for x in nums if x % 2 == 1]
print(odd_squares) # Prints "[0, 4, 16]"
[1, 9]
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
if x ** 2 % 2:
squares.append(x ** 2)
squares
[1, 9]
d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data
print(d['cat']) # Get an entry from a dictionary; prints "cute"
print('cat' in d) # Check if a dictionary has a given key; prints "True"
d['fish'] = 'wet' # Set an entry in a dictionary
d
cute True
{'cat': 'cute', 'dog': 'furry', 'fish': 'wet'}
# print(d['monkey']) # KeyError: 'monkey' not a key of d
print(d.get('monkey')) # Get an element with a default; prints "N/A"
None
d['fish']
'wet'
try:
d['monkey']
except:
print('None')
None
print(d.get('monkey'))
None
d = {'person': 2, 'cat': 4, 'spider': 8}
for key in d.keys():
print(key)
person cat spider
for val in d.values():
print(val)
2 4 8
for key, val in d.items():
print(key, val)
person 2 cat 4 spider 8
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 5 for x in nums}
print(even_num_to_square)
{0: 0, 1: 1, 2: 32, 3: 243, 4: 1024}
animals = {'cat', 'dog'}
print('cat' in animals) # Check if an element is in a set; prints "True"
print('fish' in animals) # prints "False"
True False
A = {'cat', 'dog'}
B = {'cat', 'fish'}
A_intersect_B = {a for a in A if a in B} # set comprehension
A_intersect_B
{'cat'}
A_intersect_B_size = len(A_intersect_B)
A_intersect_B_size
1
A_union_B_size = len(A) + len(B) - len(A_intersect_B)
A_union_B_size
3
def jaccard_similarty(A,B):
"""This function computes jaccard similarity"""
A_intersect_B = {a for a in A if a in B}
A_intersect_B_size = len(A_intersect_B)
A_union_B_size = len(A) + len(B) - len(A_intersect_B)
return A_intersect_B_size / A_union_B_size
jaccard_similarty(A,B)
0.3333333333333333
t = (5, 6, 5)
t
(5, 6, 5)
t[2] = 9
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-78-38eb177fe087> in <module>() ----> 1 t[2] = 9 TypeError: 'tuple' object does not support item assignment
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-15, 0, 81]:
print(sign(x))
negative zero positive
class Greeter():
# Constructor
def __init__(self, name):
self.name = name # Create an instance variable
# Instance method
def greet(self, loud=False):
if loud:
print('HELLO, ', self.name.upper())
else:
print('Hello, ', self.name)
g = Greeter('Fred') # Construct an instance of the Greeter class
g.greet() # Call an instance method; prints "Hello, Fred"
Hello, Fred
g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"
HELLO, FRED