Tips for Python

Ignacio Ruiz
2 min readJun 29, 2021

The continuation

Hey! Welcome back. Today I’ll coclude my tips for Python series with the last ones that I have.

Lets start with:

Transpose a Matrix

So, when it comes to matrices, sometimes we need to make the columns into rows. In python we can achieve it by designing some loop structure to iterate through the elements in the matrix and change their places or we can use the following zip() function in conjunction with the * operator to unzip a list which becomes the transpose of the given matrix.

Let’s check it out!

x = [[31,17],
[40 ,51],
[13 ,12]]
print (zip(*x))
#output
[(31, 40, 13), (17, 51, 12)]

Print a string N Times

Usually, If we need to have a string printed several times, we would have to use a loop. But python has a simple trick involving a string and a number inside the print function.

str ="Point";
print(str * 3);
#output
PointPointPoint

Reversing List Elements Using List Slicing

Lastly, list slicing is a very powerful technique in python which can also be used to reverse the order of elements in a list. Super usefull in unexpected codes.

#Reversing Strings
list1 = ["a","b","c","d"]
print list1[::-1]

# Reversing Numbers
list2 = [1,3,6,4,2]
print list2[::-1]
#output
['d', 'c', 'b', 'a']
[2, 4, 6, 3, 1]

Hope you enjoyed this series and use it to your advantage! :D

--

--