Every Smart Python Programmer Should Know These

Top 20 Tricks in Python That Can Make You a Smart Python Programmer

Nickson Joram
Analytics Vidhya
Published in
7 min readOct 12, 2021

--

What makes the difference between a good programmer and a smart programmer? Obviously, the way how the programmer performs. In this article, we are going to see some tricks which we can use in Python. These can make us look smarter than a good Python Programmer.

Photo by Kevin Canlas on Unsplash
  1. Reversing a String

We’ll use the straightforward concepts of string slicing and negative indexing. We know that Python can have a negative index, so we just slice it and don’t include any initial and final values, just a range of -1, which means it will start from the last index and go back to the first, thus reversing it.

>>> text = "i am going to reverse it"
>>> print(text[: : -1])
ti esrever ot gniog ma i

Trust me, you can’t do this coolest way in any other language.

2. _ Operator

This returns the last output.

>>> 10-9
1
>>> _
1

3. Numerous inputs from the user at once

The usual way is getting the input separately like this

>>> a = input("Enter the first letter : ")
Enter the first letter : a
>>> b = input("Enter the next letter : ")
Enter the next letter : b
>>> print(a)
a
>>> print(b)
b

So how to make it smarter?

>>> a, b = input("Enter the first 2 letters : ").split()
Enter the first 2 letters : a b
>>> print("First letter ", a)
First letter a
>>> print("Next letter ", b)
Next letter b

The split() function is useful for obtaining multiple inputs from the user. It divides the given input using the separator specified. If no separator is specified, any white space is considered a separator.

4. The Walrus(:=) Operator

One of Python’s most recent additions is the Walrus operators. Python 3.8 is the most recent version to include it. It is an assignment interpretation that allows assignments to take place directly within the interpretation.

The usual way is

>>> list = ['a', 'b', 'c']
>>> n = len(list)
>>> if n > 2 :
print(n)
3

In this example, we declare a list and then declare a variable ’n’ to assign the value of the list’s length.

By employing Walrus operators,

>>> list = ['a', 'b', 'c']
>>> if(n:=len(list) > 2):
print(n)
True

We declare and assign the value at the same time in this case. That is the Walrus operator’s power.

5. List comprehension

In Python, list comprehension is a graceful way to define and create lists. Lists, like Mathematical statements, can be created in a single line. The syntax of list comprehension is simpler to understand. It’s a clever way to work with lists.

Let’s print square values of odd numbers in a range.

The normal method

>>> odd_squares = []
>>> for i in range(11, 29):
if i % 2 == 1:
odd_squares.append(i**2)
>>> print(odd_squares)
[121, 169, 225, 289, 361, 441, 529, 625, 729]

Using List Comprehension

>>> odd_squares = [x ** 2 for x in range(11, 29) if x % 2 == 1]
>>> print(odd_squares)
[121, 169, 225, 289, 361, 441, 529, 625, 729]

We’ve brought loops and the conditions in one single line and this is called List Comprehension.

6. Fibonacci series

That is the best-loved coding problem at any university in the world. It is resolved through recursion and dynamic programming approaches and other programming languages take a numerous number of codes. And once again, I have a one-line solution for you. Throw this code at your lecturer to astound him or her.

>>> fibonacci = lambda n : n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)
>>> result = fibonacci(20)
>>> print(result)
6765

Don’t blame me for ruining your 20+ lines of code in Java or C++ or any other.

7. Removing duplicates from a List

Lists may contain duplicate elements. However, there are times when we don’t want duplicate elements in the list. Let’s take a look at how that can be accomplished.

>>> Numbers = [5, 7, 1, 2, 3, 1, 5, 6, 6, 3, 2]
>>> print("Original List = ", Numbers)
Original List = [5, 7, 1, 2, 3, 1, 5, 6, 6, 3, 2]
>>> Numbers = set(Numbers)
>>> print("After removing duplicates = ", Numbers)
After removing duplicates = {1, 2, 3, 5, 6, 7}
>>> type(Numbers)
<class 'set'>

Class is set. If you want to keep it as a list try this.

>>> Numbers = [5, 7, 1, 2, 3, 1, 5, 6, 6, 3, 2]
>>> print("Original List = ", Numbers)
Original List = [5, 7, 1, 2, 3, 1, 5, 6, 6, 3, 2]
>>> Numbers = sorted(set(Numbers))
>>> print("After removing duplicates = ", Numbers)
After removing duplicates = [1, 2, 3, 5, 6, 7]
>>> type(Numbers)
<class 'list'>

8. Manipulating Tuples

A tuple is a collection that is both ordered and immutable. When we say that tuples are ordered, we indicate that the items are in a specific order that will not change. Tuples are immutable, which means we can’t change, add, or remove items after they’ve been created.

But we can change a tuple. How? Check the below codes.

>>> tuple_a = (10, 20, 30, 40, 50, 60)
>>> list_a = sorted(set(tuple_a))
>>> list_a.append(60)
>>> tuple_a = tuple(list_a)
>>> print(tuple_a)
(10, 20, 30, 40, 50, 60, 60)

You can call list(tuple_a) also, the overall intention is to convert the tuple to a list and modify it before converting back as a tuple.

9. Lambda Function

This is one of the anonymous functions because these functions do not have names. These are extensively used in Data Science, Machine Learning, Django backends, and other areas. Let’s look at an example of adding two numbers.

Normal function,

>>> def addition(a, b) : return a+b>>> addition(5, -2)
3

Lambda Function

>>> addition = lambda a, b : a+b
>>> addition(5, -3)
2

10. Palindrome

I’m sure you’ve encountered this question before. It is one of the university’s most popular problems. Have you ever considered doing something with just one line of code? Look at this.

>>> text = "wowow"
>>> palindrome = bool(text.find(text[: : -1]) + 1)
>>> print(palindrome)
True

11. Multi-args Function

It’s one of Python’s nicest tricks. Let’s say you’re writing a function and you’re not sure how many arguments will be passed in from the user. So, how do we declare the function’s parameters? Here’s an illustration of a Multi-args function that will add any number of values passed by the user.

>>> def addition(*number) :
result = 0
for i in number :
result = result + i
return result
>>> print(addition(6, -5))
1
>>> print(addition(6, -5, 4, -6, 8, 12))
19

12. Swapping numbers

When it comes to data structures and algorithms, swapping is a crucial concept. Let’s take a look at how we can swap numbers in Python.

In the normal method, we’ll need to create a temporary variable to temporarily store a value so that the other one becomes empty and we can swap the values.

>>> a, b = 5, 15
>>> temp = a
>>> a = b
>>> b = temp
>>> print('The value of a after swapping is ',a)
The value of a after swapping is 15
>>> print('The value of b after swapping is ',b)
The value of b after swapping is 5

Let me now demonstrate a simple Python trick for swapping numbers.

>>> a, b = 5, 15
>>> a, b = b, a
>>> print('The value of a after swapping is ',a)
The value of a after swapping is 15
>>> print('The value of b after swapping is ',b)
The value of b after swapping is 5

13. Concatenating Strings

Let’s see how we can create a string from a list of characters.

>>> letters = ['f', 'o', 'o', 'd']
>>> text = ''.join(letters)
>>> print(text)
food

14. Using ZIP with lists

>>> language = ['python', 'java', 'c']
>>> creators = ['guido van rossum', 'james gosling', 'denis ricthie']
>>> for language, creators in zip(language, creators):
print(language, creators)
python guido van rossum
java james gosling
c denis ricthie

15. Converting lists into a dictionary

This is one of the most useful tricks when working on real-world Django and Machine Learning projects. As before, use the zip() function, but this time call it from the dictionary constructor.

>>> language = ['python', 'java', 'c']
>>> creators = ['guido van rossum', 'james gosling', 'denis ricthie']
>>> dictionary = dict(zip(language, creators))
>>> print(dictionary)
{'python': 'guido van rossum', 'java': 'james gosling', 'c': 'denis ricthie'}

16. Print list elements in any order

If you really need to print the values of a list in various combinations, you can assign the list to a sequence of variables and decide which order to print the list in programmatically.

>>> List = [10, 20, 30, 40]
>>> a, b, c, d = List
>>> print(a, b, c, d)
10 20 30 40
>>> print(b, c, a, d)
20 30 10 40

17. Print a string n times

>>> text = 'Hi '
>>> print(text * 5)
Hi Hi Hi Hi Hi

18. Merging two dictionaries

>>> p = {'a': 10, 'b': 20}
>>> q = {'b': 30, 'c': 40}
>>> r = {**p, **q}
>>> print(r)
{'a': 10, 'b': 30, 'c': 40}

19. Mapping function

>>> x = [1, 2, 3]
>>> y = map(lambda x : x + 1 , x)
>>> print(sorted(set(y)))
[2, 3, 4]

20. Shutting down a computer

Let’s see how we can shut down a computer with a single line of code. We will use the OS module for this. It is one of the most important Python modules, with numerous other functions.

CAUTION: BEFORE TRYING THIS, APPRECIATE MY WORK IF YOU LIKE AS YOUR MACHINE GOING TO BE SHUT DOWN!

>>> import os
>>> os.system(‘shutdown -s’)

That’s it.

Is that all about?

Don’t stay apart. Just do more practice and that has to be in an appropriate way. Never forget, Perfect practice makes a man perfect!

Hope this can help. Share your thoughts too.

--

--

Analytics Vidhya
Analytics Vidhya

Published in Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Nickson Joram
Nickson Joram

Written by Nickson Joram

MSc | UK | Ex - Virtusan | Learner

No responses yet