DEV Community

Akshay Varshney
Akshay Varshney

Posted on

1

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

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay