0

Shorten codes? (Python 3)

I always end up elongating my codes unnecessarily. Any tips on how to avoid using extra lines? Is it a good strategy, or rather investment, to look up shortcuts in every step; is it merely a waste of time?

13th May 2020, 12:19 AM
Md. Niamul Ahad Chowdhury
Md. Niamul Ahad Chowdhury - avatar
3 Respostas
+ 2
Ever heard of the term "Pythonic"? Well, it is used by Python coders to describe a clean and readable code, this can cause a longer or shorter code depending on the situation, things can be more clear by three examples:- Suppose that we want to get only the even numbers in a list of numbers, this can be approached by different ways 1. filter(lambda x: x % 2 == 0, our_list) 2. [i for i in our_list if i % 2 == 0] 3. for j in our_ list: if j % 2 == 0: # do something Those three ways accomplish the same result, but which one do you think is better? In other words, which one is more Pythonic? Well, it is the second one ( called list comprehensions). But it is not the best in every case, there are cases when we want to execute more complicated code on an iterable (in our case a list), or even if we want to do more complex things with the even numbers we have, the third one is longer yet can be more Pythonic in such cases.
13th May 2020, 1:00 AM
Ali Abdelhady
Ali Abdelhady - avatar
+ 1
Most of the methods to shorten code tell you it has no impact on the actual speed of the program. But it can potentially make your code more readable and save you a lot of time writing it.
13th May 2020, 12:37 AM
Slick
Slick - avatar
+ 1
Part 2:- If your code mainly depends on functions and you have one function that is gonna do the job for you then the first way might be a good choice knowing these different ways to do things will give you more control over the length of your code in a more readable"Pythonic" way
13th May 2020, 1:06 AM
Ali Abdelhady
Ali Abdelhady - avatar