by Riddhima Singh
1384
As we all know, Python is a versatile language with lots of possibilities.
So in this article, we will see how to write python code with some tricks so that it can reduce the number of lines you have to write to get the same functionality. Irrespective of your experience these tricks will help you.
We've covered the tricks with lists, strings, tuples, sets, etc.
Table of Contents
1. Reverse a "List"
Generally, In python, we use the reverse()
function to reverse a list but we can do it another with a simple trick. And the trick is 👇
Code
# An example of a list
a=["apple", 30, "mango", 50, "banana", 10]
# TRICK: to reverse a list
print(a[::-1])
Output
# Reversed list
[10, 'banana', 50, 'mango', 30, 'apple']
2. Combining two different lists with "zip()" method
The zip() method takes one or more iterables (such as list, tuple, string, etc.) and constructs the iterator of tuples where each tuple contains elements from each iterable that you have provided.
Code
# First iterable
a=[1,2,3,4,5,6]
# Second iterable
b=["A", "B", "C", "D", "E", "F"]
# Creating an iterator object (type zip)
zip_obj = zip(a, b)
# Now we can iterate through this iterator object
for item in zip_obj:
# Iterm is a tuple
print(item)
Output
(1, 'A')
(2, 'B')
(3, 'C')
(4, 'D')
(5, 'E')
(6, 'F')
3. Convert a string to a List with the "split()" method
If you have a string and you want to convert that into a list so we can do it simply by using the split()
method.
Code
string="Splitting Strings are easy with this method"
list_of_string_items = string.split()
print(list_of_string_items)
Output
['Splitting', 'Strings', 'are', 'easy', 'with', 'this', 'method']
Wait!✋ After splitting strings, we can even join them with the help of join()
function.
Code
a_join = ["We", "can", "easily", "join", "strings ", "using", "join"]
print(" ".join(a_join))
Output
"We can easily join strings using join"
4. Transpose a matrix(2D Array)
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, the transpose of A[ ][ ] is obtained by changing A[i][j] to A[j][i].
So to do that, we can use a simple trick with the help of the zip()
function.
Code
# Initial matrix
matrix = [[1, 2, 3],
[6, 7, 8]]
# Transposing
new_matrix_object = zip(*matrix)
# Printing transposed matrix
for row in new_matrix_object:
print(row)
Output
(1, 6)
(2, 7)
(3, 8)
5. Iterate with enumerate() instead of range(len())
The method enumerate()
keeps track of both the index and the number by iterating through a sequence with enumerate() but most people use range(len()).
Although range(len()) works, it's much nicer to use the built-in enumerate function here. The current index and item are returned as a tuple. This allows us to directly check the value and access the item.
Code
numbers = ["one", "two", "three", "four", "five"]
# Example with enumerate
for index, value in enumerate(numbers):
print(index, value)
Output
0 one
1 two
2 three
3 four
4 five
6. Copy a "List"
Python's list-slicing feature can be used to copy a list. And we can do it by just writing a single line.
Code
list_1 = [1, 2, 3, 4, 5, 6]
print("Address of list_1: ",id(list_1))
# copy list
list_2 = list_1[:]
print("Address of list_2: ",id(list_2))
Output
Address of list_1: 140304900372800
Address of list_1: 140304900407616
7. Negative indexing to access list items
If you know then good if you don't know that we can access the list of items with negative indexes then check this trick.
Code
numbers = [1, 2, 3, 4, 5, 6]
# Accessing list items with negative indexing
print(numbers[-1])
print(numbers[-3])
Output
6
4
8. F-String formating
This is one of the methods to format the string in Python. And the easiest method without much confusion.
Code
# Let say i want to print "Hi I'm John and I'm 19 years old!"
name = "John"
age = 19
# F-string formatting
print(f"Hi, I'm {name} and I'm {age} years old!")
Output
"Hi, I'm John and I'm 19 years old!"
F-strings are also used to print the value along with an identifier name.
Code
x = 10
y = 20
print(f"{x = }, {y = }")
Output
x = 10, y = 20
9. Remove duplicate entries from lists
You can remove duplicate elements from a list by converting it to a set (then back to a list). Sets cannot contain duplicates, unlike lists. This is what helped us remove the duplicate elements from our list.
Code
a = [1 , 2 , 3 , 4 , 2 , 3 , 4 , 5 , 6 , 7 , 3 , 2 ]
print(list(set(a)))
Output
[1, 2, 3, 4, 5, 6, 7]
10. Save memory with generators
If you are working with a large dataset and if you want to save a lot of memory while performing that task then you can use a generator instead of using a list.
Code
import sys
# Creating a sum of the 10000 numbers with List
number_list = [i for i in range(10000)]
print(sum(number_list))
# Checking the memory it is consuming to perform this task with List
print(sys.getsizeof(number_list), "bytes")
# Creating a sum of the 10000 numbers with a Generator
number_generator = (i for i in range(10000))
print(sum(number_generator))
# Checking the memory it is consuming to perform this task with Generator
print(sys.getsizeof(number_generator), "bytes")
Output
49995000
85176 bytes
49995000
112 bytes