DEV Community

Akshay Varshney
Akshay Varshney

Posted on

Few awesome tricks in Python

Few awesome tricks with Python that will save both your time and extra Lines:

A. Assigning Values according to the condition:

Normal Code:πŸ‘‰
Alt Text
Better way:
In spite of writing these lines of code what we can do is use in this way.πŸ‘‡
Alt Text

B. Using indexes and values of a list at the same time

Normal Code: πŸ‘‡
Alt Text

Better way:
Using the enumerate function. Enumerate is a function that will return both the values and index that we are looping over the list.πŸ‘‡
Alt Text

C. Unpacking
Suppose there are a few variables in code and we have to use some of them then we can use the unpacking technique.
Normal code: πŸ‘‡
Alt Text

Better way:
If we are using only one variable then we can get rid of that by using _

Alt Text

D. Reverse a list or string:
In python, we can reverse a list or a string by just using one line of code.
Better way : πŸ‘‰
Alt Text

E. Swap numbers without using temp variable:
Normal code:πŸ‘‰
Alt Text

Better way: πŸ‘‰
Alt Text

F. Looping over multiple lists at the same time

Suppose there are multiple lists and we have to loop over all of them and use them in one statement or function, then in that case we can use the zip function like this: πŸ‘‡
Alt Text

That's it for this one. Thanks for reading :)

Top comments (0)