Five++ cool Python snippets (Part - 2)

Five++ cool Python snippets (Part - 2)

Useful Python snippets that can actually save your time

ยท

4 min read

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 ๐Ÿ˜›)

Did you find this article valuable?

Support The Trojan by becoming a sponsor. Any amount is appreciated!