Trick and tips for better code in python
This notes are base in the Medium post called "five Python tricks you need to learn today" and different articles or answers i found on Internet.
TIp 1: Clean - Powerful One-liners¶
Conditional statements¶
A normal If conditional will look like this:
but this can be one line, it can be simplified in this way:
for loops¶
for example, doubling a list of integers in four lines:
and it can be simplify to just one line:
Tip 2: String Manipulation¶
Reverse a string¶
we can use ::-1 to reverse a string, like this:
join strings¶
we can print the result of join different strings, or item of a list together:
let say we have this:
so we can use join() method to create the outcome:
Tip 3: Replace loops for Map, Filter, and Reduce¶
In some cases what we want to achieve with the loops can be done by map(), filter(), and reduce(), we need to keep in mine the following:
- Map: Apply the same set of steps to each item, storing the result.
- Filter: Apply validation criteria, storing items that evaluate True.
- Reduce: Return a value that is passed from element to element.
here a simple example, first how it will be done by loops
now let's do it with the functions
map()andfilter()are native available, butreduce()is part of the libraryfunctools.- The lambda expression is the first argument, and the second is an iterable.
- The lambda expression for
reduce()requires two arguments: the accumulator (the value that is passed to each element) and the individual element itself.