Tips For Python

Ignacio Ruiz
2 min readJun 26, 2021

--

The one with simple tricks

Hey! This time I’m bringing you some cool pythonic tricks that can come in handy in just every day coding. Lets start with:

Reversing a List!

Bet you didn’t know there was an easy way! To do so, all you have to use is the reverse() function. This function can handle both numeric and string data types in a list.

Lets take a look!

names = ["Tom", "Lain","Sam" ]
names.reverse()
print(names)
#output
['Sam', 'Lain', 'Tom']

Easy! now lets look at:

Print list elements in any order!

So, lets say you need to print the values of a list in different orders. Well, you can assign the list to a series of variables and then decide the order in which you want to print the list.

Lets see how that looks!

numbers = [1,2,3]
a, b, c = numbers
print(b, a, c )
print(c, b, a )
#output
(2, 1, 3)
(3, 2, 1)

Swap two numbers using a single line of code!

When it comes to swapping of numbers usually requires storing of values in temporary variables. But with this python trick we can do that using one line of code and without using any temporary variables. This can be done with any variable in python, just be careful to keep track on your variables!

That would look like:

x,y = 11, 34
print x
print y
x,y = y,x
print x
print y
#output
11
34
34
11

Using the zip() function

Let’s say we need to join many iterator objects like lists to get a single list. To do this, we can use the zip() function. This result shows each item to be grouped with their respective items from the other lists that we want to join.

Let’s look at it:

Y = (1999, 2003, 2011, 2017)
M = ("Jan", "Feb", "Mar", "Apr")
D = (11,21,13,5)
print zip(Y,M,D)
#output
[(1999, 'Jan', 11), (2003, 'Feb', 21), (2011, 'Mar', 13), (2017, 'Apr', 5)]

There you go! It’s super easy to speed up your coding, or learn something new. Hope you like these tips!

--

--

Ignacio Ruiz
Ignacio Ruiz

Written by Ignacio Ruiz

A Data Scientist in the making!

No responses yet