circuit

11 Python Tricks to Boost Your Python Skills Significantly

You won't believe how much easier things will become in Python with these tricks!




Photo by Martin Shreder on UnsplashPhoto by Martin Shreder on Unsplash

One reason why I like Python so much is that exploring new things in Python is really a big joy.

1- Remove repeated items from a list

We can use a collaboration of list and set to remove repeated items. set is a built-in data type that stores unique data values.

Example 1:

>>> numbers = [1, 2, 2, 3, 3, 3]
>>> print(list(set(numbers)))

Output:

[1, 2, 3]

Example 2:

>>> colors = ['blue', 'red', 'red', 'blue', 'red']
>>> print(list(set(colors)))

Output:

['blue', 'red']

2- Zip Your Data

You can group two iterable objects in Python with zip().

Example 1:

>>> names = list(zip((1, 2), ['Anna', 'Alice']))
>>> print(names)

Output:

[(1, 'Anna'), (2, 'Alice')]

Example 2:

>>> names = list(zip(('Mrs', 'Mr'), ['Anna', 'Jack']))
>>> print(names)

Output:

[('Mrs', 'Anna'), ('Mr', 'Jack')]

3- Reverse Lists

List slicing is a very powerful tool in Python. It can be used to reverse the order of elements in a list.

Example 1:

>>> numbers = [1, 2, 3, 4, 5]
>>> print(numbers[::-1])

Output:

[5, 4, 3, 2, 1]

Not only lists but also strings can be reversed with slicing.

Example 2:

>>> s = "Hello"
>>> print(s[::-1])

Output:

olleH

4- Count all occurrences

You can count how many times a value exists in a list with the help of collections module.

Example 1:

>>> from collections import Counter

>>> numbers = [1, 1, 1, 2, 1, 4, 4, 4, 3, 6]
>>> c = Counter(numbers)
>>> print(c)

Output:

Counter({1: 4, 4: 3, 2: 1, 3: 1, 6: 1})

You can use the same on strings without hesitation:

Example 2:

>>> from collections import Counter

>>> ch = "aabcaaabccaaaa"
>>> c = Counter(ch)
>>> print(c)

Output:

Counter({'a': 9, 'c': 3, 'b': 2})

5- Check Your Python Version

You can easily learn your Python version with sys module.

>>> import sys
>>> print(sys.version_info)

Output:

sys.version_info(major=3, minor=7, micro=4, releaselevel='final', serial=0)

Now I am using Python 3.7.4. It is a little bit outdated. I have to update it as soon as possible!

6- Print your data with separators:

Data to be printed out looks awesome!

Example 1:

>>> username = "user"
>>> host = "mail.com"

>>> print(username, host,sep="@")

Output:

user@mail.com

Example 2:

>>> print('25','06','2021', sep**=**'-')

Output:

25-06-2021

7- Swap dictionary key & values:

You can swap keys & values of a dictionary in a single line.

Example 1:

>>> mydict= {1: 11, 2: 22, 3: 33}

>>> mydict = {i: j for j, i in mydict.items()}

>>> print(mydict)

Output:

{11: 1, 22: 2, 33: 3}

Example 2:

>>> mydict= {'John': 'Tesla', 'Jane': 'BMW'}

>>> mydict = {i:j for j,i in mydict.items()}

>>> print(mydict)

Output:

{'Tesla': 'John', 'BMW': 'Jane'}

If it’s not clear for you, spent some time to understand the idea.

(Hint: What does mydict.items() return?)

8- Get indexes of all letters from a string

How to get index values of all characters in a string?

Example 1:

>>> s = ”Python”
>>> e = enumerate(s)
>>> print(list(e))

Output:

[(0, 'P'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n')]

Example 2:

>>> s = ”Hello”
>>> e = enumerate(s)
>>> print(list(e))

Output:

[(0, 'H'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]

9- Check if objects are the same with is & not is

Nowadays everybody somehow hears this feature. I put these lines to test your knowledge. Can you correctly answer to following lines? If you make a mistake, making a review will be great for you.

Example 1:

>>> t1 = ["Africa"]
>>> t2 = ["Africa"]
>>> t3 = t2

>>> print(t1 is t2)
>>> print(t1 is t3)
>>> print(t1 is not t2)

Output:

False
False
True

Example 2:

>>> t1 = "Africa"
>>> t2 = "Africa"
>>> t3 = t2

>>> print(t1 is t2)
>>> print(t1 is t3)
>>> print(t1 is not t2)

Output:

True
True
False

10- Concatenate tuples

Concatenation is not special only for lists. Tuples can also be concatenated.

Example 1:

>>> colors = ('blue', 'red') + ('yellow', 'green')
>>> print(colors)

Output:

('blue', 'red', 'yellow', 'green')

You can also concatenate more than two tuples:

Example 2:

>>> numbers = (1, 2) + (3,) + (4, 5)
>>> print(numbers)

Output:

(1, 2, 3, 4, 5)

If you want to learn more advanced stuff about tuples, you should look at this amazing article. Improve Your Python Coding: Tuple Packing and Unpacking *Packing and unpacking really improve the readability of your code. Let’s review them and learn using underscore and…*levelup.gitconnected.com

11- Use return instead of return None

In Python, if return value of a function is not specified, the function returns None by default.

Example 1:

>>> def double(n):
...     print(n * 2)

>>> double(5)
>>> print(type(double(5)))

Output:

10
<class 'NoneType'>

Example 2:

>>> def add_zero(l):
...     l.append(0)

>>> l = [1, 2, 3]
>>> add_zero(l)

>>> print(l)
>>> print(type(add_zero(l)))

Output:

[1, 2, 3, 0]
<class 'NoneType'>

Thank you for reading this article! If you have any other tips, share them with us in the comments!

If you look for further tricks, you should check this amazing article: 5 Ways to Make Your Python Code Faster *Let’s learn how to make Python faster!*python.plainenglish.io




Continue Learning