The Beauty of Python — Part 1

Balaji MJ
2 min readSep 17, 2020

This is the series of articles which I’m going to publish about using Python in the Most Elegant and advanced level.

In this article, we are going to use Python Zip.

Wanna Merge two or more list and generate in the result of tuples? Use Python Zip!

This is one of the examples of using Python Zip Function.

The Zip() function in Python is defined as zip(*iterables). This function takes the arguments as iterables and returns an iterator.

So what are those iterables which are arguments?

zip() function can accept any type of iterable, such as files, lists, tuples, dictionaries, sets and so on. But the iterator generates a series of tuples.

Let’s solve an LeetCode Problem using Python Zip()

Given a string s and an integer array indices of the same length.

The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.

Return the shuffled string.

We have to return the shuffled string with starting from sorted positions.

Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.

As you can see in this problem, we have used Zip function to map both the indices and string and sorted to rearrange the indices.

Let’s see another LeetCode Problem to explain in detail.

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Input: ["flower","flow","flight"]
Output: "fl"

You can see in this problem, I have used zip(*strs), the input list of strings as iterable

The Zip() function can receive multiple iterables as input. It returns an iterator that can generate tuples with paired elements from each argument. The iterator result is quite useful when processing multiple iterables in a single loop and perform operations on their items in the same instance.

In the next article, we will discuss Python Lambda.

--

--

Balaji MJ

I write about Software Engineering, Backend Development, Algorithmic Trading, Quantitative Finance, and our Mind and Universe.