Unzip list Python

Last update on October 09 2020 09:17:11 [UTC/GMT +8 hours]

Write a Python program to unzip a list of tuples into individual lists.

Sample Solution:-

Python Code:

#create a tuple l = [[1,2], [3,4], [8,9]] print[list[zip[*l]]]

Sample Output:

[[1, 3, 8], [2, 4, 9]]

Flowchart:


Python Code Editor:

Have another way to solve this solution? Contribute your code [and comments] through Disqus.

Previous: Write a Python program to convert a tuple to a dictionary.
Next: Write a Python program to reverse a tuple.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

In line search for multiple prefixes in a string:

Example:

print["//www.google.com".startswith[["//", "//"]]] print["//www.google.co.uk".endswith[[".com", ".co.uk"]]]

Output:

True True

Summary: in this tutorial, you’ll learn how to unpack a list in Python to make your code more concise.

Introduction to the list unpacking

The following example defines a list of strings:

colors = ['red', 'blue', 'green']

Code language: Python [python]

To assign the first, second, and third elements of the list to variables, you may assign individual elements to variables like this:

red = colors[0] blue = colors[1] green = colors[2]

Code language: Python [python]

However, Python provides a better way to do this. It’s called sequence unpacking.

Basically, you can assign elements of a list [and also a tuple] to multiple variables. For example:

red, blue, green = colors

Code language: Python [python]

This statement assigns the first, second, and third elements of the colors list to the red, blue, and green variables.

In this example, the number of variables on the left side is the same as the number of elements in the list on the right side.

If you use a fewer number of variables on the left side, you’ll get an error. For example:

colors = ['red', 'blue', 'green'] red, blue = colors

Code language: Python [python]

Error:

ValueError: too many values to unpack [expected 2]

Code language: Python [python]

In this case, Python could not unpack three elements to two variables.

Unpacking and packing

If you want to unpack the first few elements of a list and don’t care about the other elements, you can:

  • First, unpack the needed elements to variables.
  • Second, pack the leftover elements into a new list and assign it to another variable.

By putting the asterisk [*] in front of a variable name, you’ll pack the leftover elements into a list and assign it to a variable. For example:

colors = ['red', 'blue', 'green'] red, blue, *other = colors print[red] print[blue] print[other]

Code language: Python [python]

Ouptut:

Code language: Python [python]

This example assigns the first and second elements of the colors list to the red and green variables. And it assigns the last element of the list to the other variable.

Here’s another example:

colors = ['cyan', 'magenta', 'yellow', 'black'] cyan, magenta, *other = colors print[cyan] print[magenta] print[other]

Code language: Python [python]

Output:

cyan magenta ['yellow', 'black']

Code language: Python [python]

This example assigns the first and second elements to variables. It packs the last two elements in a new list and assigns the new list to the other variable.

Summary

  • Unpacking assigns elements of the list to multiple variables.
  • Use the asterisk [*] in front of a variable like this *variable_name to pack the leftover elements of a list into another list.

Did you find this tutorial helpful ?

Photo by Ilya Pavlov on Unsplash

Let’s say that we have two lists, one that includes first names, and the other includes last names. We would like to somehow combine the first names with the corresponding last names as tuples. In other words, we would like to combine elements from multiple iterables that have the same index together in a list of tuples:

We can accomplish this with the zip[] function, which is a built-in python function. The zip[] function is named due to its analogous mechanism as physical zippers. When you zip something, you bring both sides together. And that’s how the zip[] function works! It brings elements of the same index from multiple iterable objects together as elements of the same tuples.

zip[*iterables]

The zip[] function takes in iterables as arguments, such as lists, files, tuples, sets, etc. The zip[] function will then create an iterator that aggregates elements from each of the iterables passed in. In other words, it will return an iterator of tuples, where the i-th tuple will contain the i-th element from each of the iterables passed in. This iterator will stop once the shortest input iterable has been exhausted.

Well, based on the above goal, we have two lists [which are iterable objects], and we would like to combine the same indexed elements from each of these lists together. Thus, we can use the zip[] function to accomplish this as follows:

Remember, the zip[] function returns an iterator. Thus, we need to use the list[] function that will use this returned iterator [or zip object] to create a list. In addition, as long as the iterables passed in are ordered [sequences], then the tuples will contain elements in the same left-to-right order of the arguments passed in the zip[] function.

Let’s say we have another list, ages, that contains the age of the corresponding individual in the other two lists, first_names and last_names. We would like to also include the ages in in the tuple with the first and last name. Well, as mentioned above, the zip[] function takes in any number of iterables.

Notice how the names_and_ages contains tuples with n elements [the same number of arguments, or iterable objects, we passed in to the zip[] function].

If we only pass in one iterable object to the zip[] function, then we will get a list of 1-item tuples as follows:

What if we pass in lists [or other iterable objects] of unequal lengths? In other words, let’s say that our last_names list contains 1 more element than first_names. Well, as mentioned above, the iterator returned by the zip[] function will stop once the shortest input iterable has been exhausted. In other words, our list of tuples will only contain the elements from the indexes that are present in all the iterables passed in to the zip[] function. Thus, the remaining elements in the longer iterables will be ignored.

If the elements in the longer iterables are needed, then we can use the itertools.zip_longest[] [zip_longest[] function located in the itertools module] function instead of zip[]. It will continue until the longest iterable is exhausted, and will replace any missing values with the value passed in for the fillvalue argument [default is None].

We can use the zip[] function to iterate in parallel over multiple iterables. Since the zip[] function returns an iterator, we can use this zip object [the iterator it returns] in a for loop. And since with each iteration of this iterator a tuple is returned, we can unpack the elements of this tuple within the for loop:

Or we can have three iterables:

Another example of parallel iteration:

We have two lists: a list of revenues and a list of costs. We would like to make a new list, profits, that is the difference between the revenues and costs. We can accomplish this using parallel iteration:

Let’s say that we have the following list of tuples:

And we want to separate the elements in these tuples into two separate lists. Well, since that is the opposite of zipping [bringing things together], it would be unzipping [taking things apart]. To unzip in python, we can use the unpacking operator * with the zip[] function as follows:

The unpacking operator * will unpack the first_and_last_names list of tuples into its tuples. These tuples will then be passed to the zip[] function, which will take these separate iterable objects [the tuples], and combines their same-indexed elements together into tuples, making two separate tuples. Lastly, through tuple unpacking, these separated tuples will be assigned to the first_names and last_names variables. We then use the list[] function to convert these tuples into lists.

In this tutorial, we looked at how the zip[] function works in python. We learned how the zip[] function operates in different scenarios, such as with one iterable, or with iterables that have unequal lengths. We then saw how we can use the zip[] function to iterate over multiple iterable objects in parallel. And lastly, we learned how to use the unpacking operator * to unzip objects in python.

Video liên quan

Chủ Đề