Python Tips
Python Tips
Python Tips
Tips
( with Code)
by Chetan Kandpal
SkyRocket your
Machine Learning
skills by applying
these basic Python
tips.
swipe
Inspired by the article by Fatos Morina.
Link: https://towardsdatascience.com/100-helpful-python-tips-you-can-
learn-before-finishing-your-morning-coffee-eb9c39e68958
print(python_version())
3.8.13
missed the following “for-else” which I also got to see for the first time a couple of
weeks ago.
This is not something that I have seen in other programming languages like Java,
Ruby, or JavaScript.
Let’s say that we are trying to check whether there are no odd numbers in a list.
In [1]:numbers = [2, 4, 6, 8, 1]
In case we find an odd number, then that number will be printed since break will be
executed and the else branch will be skipped.
Otherwise, if break is never executed, the execution flow will continue with the else
branch.
No odd numbers
In [3]:one
Out[3]: 1
In [4]:two
Out[4]: 2
In [5]:three
Out[5]: 3
In [6]:four
Out[6]: 4
In [7]:five
Out[7]: 5
scores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]
print(heapq.nlargest(3, scores)) # [91, 87, 82]
In [12]:my_list = [1, 2, 3, 4]
print(my_list) # [1, 2, 3, 4]
print(*my_list) # 1 2 3 4
[1, 2, 3, 4] 1 2
3 4
This can be helpful in situations where we want to pass all elements of a list as
method arguments:
In [13]:def sum_of_elements(*arg):
total = 0
for i in arg:
total += i
return total
10
[2, 3, 4, 5, 6, 7]
In [16]:one
Out[16]: 1
In [17]:two
Out[17]: 2
In [18]:three
Out[18]: 3
In [19]:four
Out[19]: 4
7. List comprehensions
You can loop through the elements in a list in a single line in a very comprehensive
way.
In [20]:numbers = [1, 2, 3, 4, 5, 6, 7, 8]
print(even_numbers) # [2, 4, 6, 8]
[2, 4, 6, 8]
{'first_element': 1, 'third_element': 3}
global variables, but they offer a more useful repr(), grouping, type-safety, and a few
other features.
class Status(Enum):
NO_STATUS = -1
NOT_STARTED = 0
IN_PROGRESS = 1
COMPLETED = 2
print(Status.IN_PROGRESS.name) # IN_PROGRESS
print(Status.COMPLETED.value) # 2
IN_PROGRE
SS 2
print(string * 5) # AbcAbcAbcAbcAbc
AbcAbcAbcAbcAbc
1 < x < 10
That is the algebraic expression that we learn in elementary school. However, you
can also use that same expression in Python as well.
Yes, you heard that right. You have probably done comparisons of such form up until
now:
1 < x < 10
In [25]:x=3
print(1<x<10)
True
This doesn’t work in Ruby, the programming language that was developed with the
as well.
I was really impressed seeing such a simple expression not being talked about more
widely. At least, I haven’t seen it being mentioned that much.
print(books.index('Mastery'))
input = "[1,2,3]"
You don’t need it in that format. You need it to be a list:
input = [1,2,3]
Or maybe you the following response from an API call:
In [2]:import ast
def string_to_list(string):
return ast.literal_eval(string)
Now you will get the result as a list, or list of lists, namely like the following:
my_list = string_to_list(string)
print(my_list)
a - b != b -a
However, we may forget the ordering of the parameters which can cause “trivial”
mistakes:
print((subtract(1, 3)))
print((subtract(3, 1)))
-2
2
To avoid such potential mistakes, we can simply use named parameters and the
ordering of parameters doesn’t matter anymore:
print((subtract(a=1, b=3)))
print((subtract(b=3, a=1)))
-2
-2
HelloWorld
Hello World
words, with, commas, in, between
day=29
month=1
year=2022
print(day,month, year,sep="/")
[email protected]
om 29/1/2022
Input In [11]
4_letters = "abcd"# this doesn’t work
^
SyntaxError: invalid decimal literal
Input In [12]
+variable = “abcd” # this doesn’t work
^
SyntaxError: invalid character in identifier
Input In [13]
number = 0110 # this doesn't work
^
SyntaxError: leading zeros in decimal integer literals are not permitted; u se
an 0o prefix for octal integers
I am not encouraging you to use it, but in case you see a weird naming of a variable
like that, know that it is actually a valid name of a variable
In [16]:print(1_000_000_000)
print(1_234_567)
100000000
0 1234567
my_list.reverse()
This
Tssu
suj si sih
sjs i
print(my_string[:3]) # Thi
is just a sentence
Thi
1.5 1
In [22]:first_list = [1, 2, 3]
second_list = [1, 2, 3]
third_list = first_list
print(third_list is first_list)
# True, since both point to the same object in memory
True
False
True
True
False
False
94607791860992
94607791861024
140279240972016
In case we assign to that variable another value, the original object is still in memory,
but the variable pointing to it is lost:
In [27]:number = 1
print(id(number))
print(id(1))
number = 3
print(id(number))
print(id(1))
9460779186099
2
9460779186099
2
9460779186105
6
34. Strings and tuples are immutable
9460779186099
2
This was already mentioned in the previous point but wanted to emphasize it since
this is quite important.
In [28]:name = "Fatos"
print(id(name))
name = "fatos"
print(id(name))
14027914085041
6
14027914058468
8
In [29]:my_tuple = (1, 2, 3, 4)
print(id(my_tuple))
140279140199136
14027914064710
4
cities.append("Berlin")
print(id(cities))
14027914013286
4
14027914013286
Here
4 is another example with sets:
In [31]:my_set = {1, 2, 3, 4}
print(id(my_set))
my_set.add(5)
print(id(my_set))
14027916698352
0
14027916698352
0
36. You can turn a set into an immutable set
This way, you can no longer modify it:
my_set.add("a")
--------------------------------------------------------------------------- AttributeError
Traceback (most recent call last) Input In [32], in <cell line: 3>()
1 my_set = frozenset(['a', 'b', 'c', 'd'])
----> 3 my_set.add("a")
In [33]:def check_number(number):
if number > 0:
return "Positive"
elif number == 0:
return "Zero"
return "Negative"
print(check_number(1))
Positive
True
True
False
65
66
67
97
keys = dictionary.keys()
values = dictionary.values()
print(list(values)) # [1, 2, 3]
[1, 2, 3]
<class 'reversed'>
In [39]:reversed_dictionary
1.0
In [41]:x = 10
y = 12
result = (x - False)/(y * True)
print(result)
0.8333333333333334
45. You can convert any data type into a
boolean value
In [42]:print(bool(.0)) # False
print(bool(3)) # True
print(bool("-")) # True
print(bool("string")) # True
print(bool(" ")) # True
False
True
True
True
True
(10+2j)
0xb
We can also use insert() to specify the index and the element where we want to insert
this new element. In our case, we want to insert it in the first position, so we use 0 as
the index:
In [45]:my_list = [3, 4, 5]
my_list.append(6)
my_list.insert(0, 2)
print(my_list)
[2, 3, 4, 5, 6]
File <tokenize>:3
else:
^
IndentationError: unindent does not match any outer indentation level
Correct way
In [48]:comparison = lambda x: print("x > 3") if x > 3 else print("x is not greater
Input In [49]
result = lambda x: if x > 3:
^
SyntaxError: invalid syntax
Correct way
In [50]:result = lambda x: x > 3
Input In [51]
comparison = lambda x: "x > 3" if x > 3
^
SyntaxError: invalid syntax
that this is a feature of the conditional expression and not of the lambda itself.
print(list(odd))
print(my_list)
[1, 3]
[1, 2, 3, 4]
print(my_list) # [1, 2, 3, 4]
1 4 7
In [55]:def range_with_zero(number):
for i in range(0, number):
print(i, end=' ')
def range_with_no_zero(number):
for i in range(number):
print(i, end=' ')
range_with_zero(3) # 0 1 2
range_with_no_zero(3) # 0 1 2
0 1 2 0 1 2
In [56]:def get_element_with_comparison(my_list):
if len(my_list) > 0:
return my_list[0]
def get_first_element(my_list):
if len(my_list):
return my_list[0]
elements = [1, 2, 3, 4]
first_result = get_element_with_comparison(elements)
second_result = get_element_with_comparison(elements)
True
55. You can define the same method multiple
times inside the same scope
However, only the last one is called, since it overrides previous ones.##
In [57]:def get_address():
return "First address"
def get_address():
return "Second address"
def get_address():
return "Third address"
Third address
dain = Engineer('Dain')
print(dain._Engineer__starting_salary) # 62000
62000
print(sys.getsizeof("bitcoin")) # 56
56
print(get_sum(1, 2, 3)) # 6
print(get_sum(1, 2, 3, 4, 5)) # 15
print(get_sum(1, 2, 3, 4, 5, 6, 7)) # 28
6
15
28
In [61]:class Parent:
def __init__(self, city, address):
self.city = city
self.address = address
class Child(Parent):
def __init__(self, city, address, university):
super().__init__(city, address)
self.university = university
ETH Zürich
In [62]:class Parent:
def __init__(self, city, address):
self.city = city
self.address = address
class Child(Parent):
def __init__(self, city, address, university):
Parent.__init__(self, city, address)
self.university = university
ETH Zürich
Note that calls to parent initializers using init() and super() can only be used
inside the child class’s initializer.
However, when you use it between two string data types, you are going to merge
them:
In [63]:print(10 + 1) # Adding two integers using '+'
print('first' + 'second') # Merging two strings '+'
11
firstsecond
In [64]:class Expenses:
def __init__(self, rent, groceries):
self.rent = rent
self.groceries = groceries
2000
500
In [65]:class Game:
def __init__(self, score):
self.score = score
first = Game(1)
second = Game(2)
True
In [66]:class Journey:
def __init__(self, location, destination, duration):
self.location = location
self.destination = destination
self.duration = duration
print(first == second)
False
sub() for -
mul() for *
truediv() for /
ne() for !=
def __repr__(self):
return repr('Rectangle with area=' + str(self.a * self.b))
print(Rectangle(3, 4))
result = string.swapcase()
print(result)
True
65. Check if all characters in a string are either
alphabets or numbers
In [70]:name = "Password"
print(name.isalnum()) # True, because all characters are alphabets
name = "Secure Password "
print(name.isalnum()) # False, because it contains whitespaces
name = "S3cur3P4ssw0rd"
print(name.isalnum()) # True
name = "133"
print(name.isalnum()) # True, because all characters are numbers
True
False
True
True
True
False
False
First
False
True
False
False
print(string.isdigit()) # False
print(string.isnumeric()) # True
False
True
string = "PYTHON"
print(string.istitle()) # False. It's titlelized version is "Python"
False
True
False
False
is_positive(-3)
Negative
physics_points = 56
history_points = 72
my_conditions = [math_points > 50, biology_points > 50,
physics_points > 50, history_points > 50]
if all(my_conditions):
print("Congratulations! You have passed all of the exams.")
else:
print("I am sorry, but it seems that you have to repeat at least one exa
if any(my_conditions):
print("Congratulations! You have passed all of the exams.")
else:
print("I am sorry, but it seems that you have to repeat at least one exa
# Congratulations! You have passed all of the exams.
True
False
print(bool({})) # False
print(bool({"a": 1})) # True
False
False
False
True
def do_nothing():
string = "inside a method"
do_nothing()
print(string) # string
string
def do_nothing():
global string
string = "inside a method"
do_nothing()
inside a method
result = Counter("Banana")
print(result) # Counter({'a': 3, 'n': 2, 'B': 1})
True
True
False
True
True
False
my_vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
current_counter = count()
for i in string:
if i in my_vowels:
print(f"Current vowel: {i}")
print(f"Number of vowels found so far: {next(current_counter)}")
Current vowel: i
Number of vowels found so far: 0
Current vowel: i
Number of vowels found so far: 1
Current vowel: u
Number of vowels found so far: 2
Current vowel: a
Number of vowels found so far: 3
Current vowel: e
Number of vowels found so far: 4
Current vowel: e
Number of vowels found so far: 5
Current vowel: e
Number of vowels found so far: 6
print(numbers[-1])
print(numbers[-4])
4
1
print(mixed_tuple[1])
print(mixed_tuple[0])
print(names.count("Besim"))
[7, 8, 9, 10] 8
You can also use slice() for other usual slicing tasks, like:
In [93]:string = "Data Science"
# start = 1, stop = None (don't stop anywhere), step = 1
# contains 1, 3 and 5 indices
slice_object = slice(5, None)
print(string[slice_object])
Science
print(my_tuple.count('a'))
3
(1, 4, 7, 10)
(4, 5, 6, 7, 8, 9, 10)
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # set()
[]
set()
{}
print(first_set.union(second_set))
{1, 2, 3, 4, 5, 6}
first_set.update(second_set)
print(first_set)
{1, 2, 3, 4, 5, 6}
print(max(set(my_list), key=my_list.count))
https://docs.python.org/3/library/copy.html#module-copy
A shallow copy constructs a new compound object and then (to the
extent possible) inserts references into it to the objects found in the
original.
A deep copy constructs a new compound object and then, recursively,
inserts copies into it of the objects found in the original.
Maybe, an even more comprehensive description can be found
here:
A shallow copy means constructing a new collection object and then
essence, a shallow copy is only one level deep. The copying process does
not recurse and therefore won’t create copies of the child objects
themselves.
A deep copy makes the copying process recursive. It means first
constructing a new collection object and then recursively populating it with
copies of the child objects found in the original. Copying an object this way
walks the whole object tree to create a fully independent clone of the original
object and all of its children.
second_list = first_list.copy()
first_list[0][2] = 831
print(first_list)
print(second_list)
second_list = copy.deepcopy(first_list)
first_list[0][2] = 831
print(first_list)
print(second_list)
KeyError: 'age'
my_dictonary = defaultdict(str)
my_dictonary['name'] = "Name"
my_dictonary['surname'] = "Surname"
print(my_dictonary["age"])
def __next__(self):
x = self.a
self.a += 2
return x
odd_numbers_object = OddNumbers()
iterator = iter(odd_numbers_object)
print(next(iterator))
print(next(iterator))
print(next(iterator))
1
3
5
[1, 2, 3, 4, 5]
print(torch)
for i in range(9):
if i not in odd_numbers:
even_numbers.append(i)
print(even_numbers)
[0, 2, 4, 6, 8]
new_groceries = sorted(groceries)
# new_groceries = ['bread', 'milk', 'tea']
print(new_groceries)
# Generate a UUID from a host ID, sequence number, and the current time
print(uuid.uuid1()) # 308490b6-afe4-11eb-95f7-0c4de9a0c5af
# Generate a random UUID
print(uuid.uuid4())
3c2ce9fc-99cd-11ed-bd1b-
d8bbc1acd933 af7edad4-c348-410d-
ac1a-fd1da7989059