DEV Community

loading...

Few awesome tricks in Python

akshayvarshney6 profile image Akshay Varshney ・2 min read

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 :)

Discussion (0)

pic
Editor guide