Python Tips 1675511822
Python Tips 1675511822
Link: https://towardsdatascience.com/100-helpful-python-tips-you-can-
learn-before-finishing-your-morning-coffee-eb9c39e68958
print(python_version())
3.8.13
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.
if number % 2 == 1:
print(number)
break
else:
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.
if number % 2 == 1:
print(number)
break
else:
No odd numbers
In [3]: one
1
Out[3]:
In [4]: two
2
Out[4]:
In [5]: three
3
Out[5]:
In [6]: four
4
Out[6]:
In [7]: five
5
Out[7]:
scores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]
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:
total = 0
for i in arg:
total += i
return total
print(result) # 10
10
print(elements_in_the_middle) # [2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7]
In [16]: one
1
Out[16]:
In [17]: two
2
Out[17]:
In [18]: three
3
Out[18]:
In [19]: four
4
Out[19]:
7. List comprehensions
You can loop through the elements in a list in a single line in a very comprehensive
way.
print(even_numbers) # [2, 4, 6, 8]
[2, 4, 6, 8]
'third_element': 3, 'fourth_element': 4}
dictionary.items() if num % 2 == 1}
{'first_element': 1, 'third_element': 3}
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_PROGRESS
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
intention of making programmers happy. This turns out to be working in JavaScript
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:
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:
return a - b
print((subtract(1, 3)))
print((subtract(3, 1)))
-2
To avoid such potential mistakes, we can simply use named parameters and the
ordering of parameters doesn’t matter anymore:
return a - b
print((subtract(a=1, b=3)))
print((subtract(b=3, a=1)))
-2
-2
print("World") # HelloWorld
HelloWorld
Hello World
day=29
month=1
year=2022
print(day,month, year,sep="/")
name@domain.com
29/1/2022
Input In [11]
Input In [12]
Input In [13]
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)
1000000000
1234567
my_list.reverse()
print(my_string[0:5]) # This
print(my_string[0:10:3]) # Tsse
This
Tssu
print(my_string[10:0:-2]) # sjs i
suj si sih
sjs i
print(my_string[:3]) # Thi
is just a sentence
Thi
print(3//2) # 1
1.5
second_list = [1, 2, 3]
print(first_list is second_list)
# False, since they have same values, but in different objects in memory
third_list = first_list
print(third_list is first_list)
True
False
True
second = "def"
second = "ab"
True
False
print(my_string.startswith("b")) # False
False
print(id(2))
print(id("string"))
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))
94607791860992
94607791860992
94607791861056
94607791860992
print(id(name))
name = "fatos"
print(id(name))
140279140850416
140279140584688
print(id(my_tuple))
print(id(my_tuple))
140279140199136
140279140647104
print(id(cities))
cities.append("Berlin")
print(id(cities))
140279140132864
140279140132864
print(id(my_set))
my_set.add(5)
print(id(my_set))
140279166983520
140279166983520
my_set.add("a")
---------------------------------------------------------------------------
----> 3 my_set.add("a")
if number > 0:
return "Positive"
elif number == 0:
return "Zero"
return "Negative"
print(check_number(1))
Positive
first_word = first_word.lower()
second_word = second_word.lower()
True
True
False
print(ord("B")) # 66
print(ord("C")) # 66
print(ord("a")) # 97
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
print(float(True)) # 1.0
1.0
In [41]: x = 10
y = 12
print(result)
0.8333333333333334
print(bool(3)) # True
print(bool("-")) # True
print(bool("string")) # 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:
my_list.append(6)
my_list.insert(0, 2)
print(my_list)
[2, 3, 4, 5, 6]
else:
File <tokenize>:3
else:
Correct way
In [48]: comparison = lambda x: print("x > 3") if x > 3 else print("x is not greater
Input In [49]
Correct way
Input In [51]
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, 9, 16]
[1, 2, 3, 4]
# 1 4 7
1 4 7
def range_with_no_zero(number):
for i in range(number):
range_with_zero(3) # 0 1 2
range_with_no_zero(3) # 0 1 2
0 1 2 0 1 2
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
def get_address():
def get_address():
Third address
self.name = name
self.__starting_salary = 62000
dain = Engineer('Dain')
print(dain._Engineer__starting_salary) # 62000
62000
print(sys.getsizeof("bitcoin")) # 56
56
result = 0
for i in arguments:
result += i
return result
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
15
28
self.city = city
self.address = address
class Child(Parent):
super().__init__(city, address)
self.university = university
ETH Zürich
self.city = city
self.address = address
class Child(Parent):
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.
60. You can redefine the “+” operator inside your own
classes
Whenever you use the + operator between two int data types, then you are going to
find their sum.
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 '+'
11
firstsecond
self.rent = rent
self.groceries = groceries
self.groceries + other.groceries)
print(total_expenses.rent) # 2000
print(total_expenses.groceries) # 500
2000
500
61. You can also redefine the “<” and “==” operators
inside your own classes
Here is another example of an operation overloadding that you can define yourself:
self.score = score
first = Game(1)
second = Game(2)
True
self.location = location
self.destination = destination
self.duration = duration
(self.duration == other.duration))
print(first == second)
False
mul() for *
truediv() for /
ne() for !=
self.b = b
def __repr__(self):
print(Rectangle(3, 4))
result = string.swapcase()
print(result)
result = string.isspace()
print(result)
True
name = "S3cur3P4ssw0rd"
print(name.isalnum()) # True
name = "133"
True
False
True
True
print(string.isalpha()) # True
string = "P4ssw0rd"
True
False
False
You can similarly remove characters from the left based on the
argument:
In [73]: string = "ffffffffFirst"
print(string.lstrip("f")) # First
First
print(string.isdigit()) # False
string = "1337"
print(string.isdigit()) # True
string = "5a"
string = "2**5"
print(string.isdigit()) # False
False
True
False
False
print(string.isdigit()) # False
print(string.isnumeric()) # True
False
True
print(string.istitle()) # False
print(string.istitle()) # True
# False, because of the first characters being lowercase in "to" and "in"
print(string.istitle())
string = "PYTHON"
False
True
False
False
is_positive(-3)
Negative
biology_points = 78
physics_points = 56
history_points = 72
if all(my_conditions):
else:
print("I am sorry, but it seems that you have to repeat at least one exa
biology_points = 78
physics_points = 56
history_points = 72
if any(my_conditions):
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.
print(bool("")) # False
True
False
print(bool(set([]))) # False
print(bool({})) # False
False
False
False
True
print(bool(None)) # False
print(bool(0)) # False
False
False
False
def do_nothing():
do_nothing()
print(string) # string
string
def do_nothing():
global string
do_nothing()
inside a method
result = Counter("Banana")
Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})
first_string = first_string.lower()
second_string = second_string.lower()
True
True
False
first_word = first_word.lower()
second_word = second_word.lower()
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:
Current vowel: i
Current vowel: i
Current vowel: u
Current vowel: a
Current vowel: e
Current vowel: e
Current vowel: e
print(numbers[-1])
print(numbers[-4])
print(mixed_tuple[1])
print(mixed_tuple[0])
('aaaaaaaaaa', 3, 4)
print(names.count("Besim"))
print(my_list[slicing]) # [4, 5, 6]
print(my_list[-3])
[7, 8, 9, 10]
You can also use slice() for other usual slicing tasks, like:
In [93]: string = "Data Science"
print(string[slice_object])
Science
print(my_tuple.count('a'))
print(my_tuple.index('f'))
print(my_tuple[::3])
(1, 4, 7, 10)
print(my_tuple[3:])
(4, 5, 6, 7, 8, 9, 10)
my_list.clear()
print(my_list) # []
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # set()
my_dict.clear()
print(my_dict)
[]
set()
{}
second_set = {1, 2, 3}
print(first_set.union(second_set))
{1, 2, 3, 4, 5, 6}
second_set = {1, 2, 3}
first_set.update(second_set)
print(first_set)
{1, 2, 3, 4, 5, 6}
print(result)
print(result.most_common())
Counter({2: 5, 1: 1, 3: 1})
print(max(set(my_list), key=my_list.count))
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)
print(my_dictonary["age"])
---------------------------------------------------------------------------
----> 2 print(my_dictonary["age"])
KeyError: 'age'
my_dictonary = defaultdict(str)
my_dictonary['name'] = "Name"
my_dictonary['surname'] = "Surname"
print(my_dictonary["age"])
def __iter__(self):
self.a = 1
return self
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))
print(list(my_set))
[1, 2, 3, 4, 5]
print(torch)
even_numbers = []
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)
print(new_groceries)
print(groceries)
groceries.sort()
print(groceries)
# Generate a UUID from a host ID, sequence number, and the current time
print(uuid.uuid1()) # 308490b6-afe4-11eb-95f7-0c4de9a0c5af
print(uuid.uuid4())
3c2ce9fc-99cd-11ed-bd1b-d8bbc1acd933
af7edad4-c348-410d-ac1a-fd1da7989059