Five++ cool Python snippets (Part - 2)

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]]

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)]

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}

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

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)]

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)]

Wrapping Up 🏁

So those were the 5++ cool quirks of python. I hope you liked them and learned something new.

Thanks for reading!

Starting out in web development?? 💻

This ebook is a comprehensive guide that teaches you everything you need to know to be a web developer through a ton of easy-to-understand examples and proven roadmaps

It contains 👇

✅ Straight to the point explanations

✅ Simple code examples

✅ 50+ Interesting project ideas

✅ 3 Checklists of secret resources

✅ A Bonus Interview prep

You can even check out a free sample from this book

and here's the link with 60% off on the original price on the complete book set ⬇

15