4 Python Things I Should Have Known Earlier But Somehow Didn’t
Some of them are really cheated
When I started learning python, there were many things I did not know.
The tips I talk about in this article are very little discussed on YouTube or anywhere in general
I assure you that understanding and mastering them will make your programmer days really (really) easier
without wasting time, let’s start
1- The Walrus Operator?(:=)
This operator allows you to assign a value to a variable in an expression
for example
let’s say we want the user to enter a number and check if it’s positive, negative or zero
here is a classic version without using the operator
number = int(input("Enter the Number: "))
if number > 0 :
print("The number is positive.")
elif number < 0 :
print("The number is negative.")
else:
print("The number is null.")
With the operator, we can assign a value and check at the same time, here is an example with the operator.
if (number := int(input("Enter the Number : "))) > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is null.")
Another example could be reading the lines of a file until an empty line is found:
with open("fichier.txt", "r") as f:
while (line := f.readline().strip()) != "":
print(line)
In this example, (line?:= f.readline().strip()) assigns the next line of the file (without the leading and trailing spaces) to the variable line, and returns this value, which is then compared to an empty string in the condition of the while.
2- The generators
Generators can be used to generate series of values without storing everything in memory.
They are useful when you work with large amounts of data.
For example:
Let’s say we want to generate the numbers of the Fibonacci sequence* up to a limit value.
??For those who have forgotten, Fibonacci is a series of numbers where each number is the sum of the two preceding numbers.
Example without Generator
def fibonacci(limit):
fib = []
a, b = 0, 1
while a < limit:
fib += [a]
a, b = b, a + b
return fib
print(fibonacci(100)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Now a version using the generator
def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
for fib in fibonacci(100):
print(fib) # 0 1 1 2 3 5 8 13 21 34 55 89
In this version, instead of adding each Fibonacci number to a list, we use the yield keyword to return each Fibonacci number on demand.
The advantage of this approach is that we don’t store all the Fibonacci numbers in memory at once. Instead, we generate each number on demand
3- The Lambda?function
In Python, a lambda function is a small, anonymous function that has no name.
It’s also called an “inline function” because it can be defined directly where it’s used, without having to be defined separately.
For example
Let’s say we want to define a function that takes a number as input and returns its square. With a normal function, we could write
def square(x):
return x**2
With a lambda function, we can write the same thing in a single line:
square = lambda x: x**2
print(square(5)) # 25
Lambda functions are often used in conjunction with higher-level functions such as map(), filter() and sorted(), which we'll now look at.
4- Map, filter and?reduce
Map() Applies a given function to each element of an iterable
?(such as a list) and returns a new iterator with the results.
For example, We have a list containing numbers
and we want to create a new list with the square of each number?:
numbers = [1, 2, 3, 4, 5]
square = list(map(lambda x: x**2, numbers))
print(square) # [1, 4, 9, 16, 25]
The filter() function takes a function and an iterator and returns a new iterator with the elements for which the function returns True.
Filter example
We have a list containing numbers
and we want to create a new list with even numbers
here’s how to do it:
numbres = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pairs = list(filter(lambda x: x % 2 == 0, numbres))
print(pairs) # [2, 4, 6, 8, 10]
And finally, the reduce() function applies a function of two arguments cumulatively to the elements of the iterable, from left to right, so as to reduce the iterable to a single value.
For example
?Let’s say we have a list of numbers and we want to calculate the product of all these numbers:
numbres = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbres)
print(product) # 120
As you can see, combining the lambda function and these functions helps you a lot, helps you with your code and is very powerful.
I hope you enjoyed this short article if you have any other suggestions don’t hesitate to add them in the comments
see you next time ??
Online Instructor at eTeacher Group
6 个月Thank you for these, I'll give them a try.