Five++ cool Python snippets (Part - 2)
Useful Python snippets that can actually save your time
Introduction ๐
Python is a beautifully designed high-level interpreted programming language that provides us with many features.
This is a gentle guide to some of those Python features that you probably might not be aware of or didn't know about that specific use-case which you'll see later in this blog.
So in continuation of my previous article, here I am sharing another 5++ tips and tricks to help you write an elegant Python code in your competitive programming journey or in general as well! ๐
1. Lambda Function
A lambda function is a small anonymous function. You can use "lambda" expression to sort a nested array by the second element
>> arr_list = [[1, 4], [3, 3], [5, 7]]
>> sorted_list = sorted(arr_list , key=lambda x: x[1])
>> sorted_list
[[3, 3], [1, 4], [5, 7]]
๐Link To Tweet
2. Counter
Counter class is a special type of object data-set provided with the collections module in Python3.
Let's say we want an ๐ฎ๐ง๐จ๐ซ๐๐๐ซ๐๐ collection where elements are stored as ๐๐ข๐๐ญ๐ข๐จ๐ง๐๐ซ๐ฒ ๐ค๐๐ฒ๐ฌ & their counts are stored as ๐๐ข๐๐ญ๐ข๐จ๐ง๐๐ซ๐ฒ ๐ฏ๐๐ฅ๐ฎ๐๐ฌ
import collections
>> A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7])
>> A
Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1})
>> A.most_common(1)
[(3, 4)]
>>A.most_common(3)
[(3,4), (1, 2), (2, 2)]
๐Link To Tweet
3. Merge 2 Dictionaries
Python 3.9 introduces Dictionary union (|)
It will return a new dictionary consisting of the left operand merged with the right operand. If a key appears in both operands, the last-seen value (i.e., from the right-hand operand) is selected.
>> d1 = {'a': 10, 'b': 5, 'c': 3}
>> d2 = {'d':6, 'c': 4, 'b': 8}
>> d1 | d2
{'a': 10, 'b': 8, 'c': 4, 'd': 6}
>> d2 | d1
{'d': 6, 'c': 3, 'b': 5, 'a': 10}
๐Link To Tweet
4. Special Strip
Can you guess what will be the output of the following python code -
>>> "three cool features in Python".strip(" Python")
Well, strip() only remove the substring " Python" from the beginning or the end but the way it does it is quite peculiar
It removes the individual characters " ", "P", "y", "t", "h", "o", "n" instead of checking the whole "Python" as a word
Note that it even considers spaces while removing characters and It is also case sensitive
๐Link To Tweet
5. [] + [] -> {}
Ever wanted to form a dictionary out of two lists??
In Python๐ it is super easy
There's a zip() function that takes several iterable objects and returns a list of tuples
Each tuple groups the elements of the input objects by their positional index
>>> x = ['a', 'b', 'c']
>>> y = [1, 2, 3]
>>> dict(zip(x, y))
{'a': 1, 'b': 2, 'c': 3}
You can even use it when you want to transpose a 2-D matrix, like this โฌ
>>> mat = [[1, 2, 3], [4, 5, 6]]
>>> list(zip(*mat))
[(1, 4), (2, 5), (3, 6)]
๐Link To Tweet
5++. Sliding Window
When I was doing competitive programming, I saw a lot of questions involving the sliding window problem
In C++ it was a little hectic, But in python, you can do it with just a few lines of code -
>>> from itertools import islice
>>> def slide(list_name, window_size):
... z = [islice(list_name, i, None) for i in range(window_size)]
... return zip(*z)
Here's the sample input and output response โฌ
>>> list(slide([1, 2, 3, 4, 5, 6, 7], 3))
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]
๐Link To Tweet
Wrapping Up ๐
So those were the 5++ cool quirks of python. I hope you liked them and learned something new.
Also if you enjoyed it, consider buying me a coffee โ
(Seriously, I'd like some cฬถoฬถfฬถfฬถeฬถeฬถ support ๐)
Other articles you might like ๐
Metrics to evaluate your Machine Learning algorithm ๐ - Evaluation Metrics for your Machine Learning algorithm that every Data Scientist must know.
Why you can't name a file 'CON' in Windows โ - Learn why Windows doesnโt allow you to create files and folders named CON, PRN, AUX, and NUL.
Five++ cool Python snippets that will blow your mind (Part - 1) ๐คฏ - Few clever yet useful Python tricks and tips that will surely make you think hard. This is Part-1 of this blog post series.
Useful Resources To Learn Web Development & To Create Your Website ๐ป - Starting with web development? Here are some resources that helped me and will be useful for you as well.