# 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](https://apoorvtyagi.tech/cool-python-snippets-that-will-blow-your-mind), 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](https://twitter.com/apoorv__tyagi/status/1356946442573725696)

## 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](https://twitter.com/apoorv__tyagi/status/1355167637660164097)


## 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](https://twitter.com/apoorv__tyagi/status/1343177309323464705)

## 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](https://twitter.com/apoorv__tyagi/status/1350057647672872961)


## 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](https://twitter.com/apoorv__tyagi/status/1323254708832628736)

## 5++.  Sliding Window

When I was doing competitive programming, I saw a lot of questions involving the [sliding window problem](https://leetcode.com/tag/sliding-window/)

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](https://twitter.com/apoorv__tyagi/status/1334200547826573312)

---

## 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 😛)

<a href="https://www.buymeacoffee.com/apoorvtyagi" target="_blank"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=apoorvtyagi&button_colour=BD5FFF&font_colour=ffffff&font_family=Comic&outline_colour=000000&coffee_colour=FFDD00"></a>

### Other articles you might like 😊

- [Metrics to evaluate your Machine Learning algorithm](https://apoorvtyagi.tech/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](https://apoorvtyagi.tech/why-you-cant-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)](https://apoorvtyagi.tech/cool-python-snippets-that-will-blow-your-mind) 🤯 - 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](https://apoorvtyagi.tech/useful-resources-to-learn-web-development-and-to-create-your-website) 💻 - Starting with web development? Here are some resources that helped me and will be useful for you as well.

