Unpacking list in list python

Unpack a tuple and list in Python

In Python, you can assign elements of a tuple or list to multiple variables. It is called sequence unpacking.

See the following article for the case of unpacking tuples, lists, and dictionaries ( dict ) as arguments with * (asterisk).

Basics of unpacking a tuple and a list

By writing variables on the left side separated by commas , , elements of a tuple or list on the right side will be assigned to each corresponding variable. The following examples use tuples, but the same is true for lists.

t = (0, 1, 2) a, b, c = t print(a) print(b) print(c) # 0 # 1 # 2 
l = [0, 1, 2] a, b, c = l print(a) print(b) print(c) # 0 # 1 # 2 

Since tuple parentheses can be omitted, multiple values can be assigned to multiple variables in a single line, as shown below.

a, b = 0, 1 print(a) print(b) # 0 # 1 

An error occurs if the number of variables and elements don’t match.

# a, b = t # ValueError: too many values to unpack (expected 2) # a, b, c, d = t # ValueError: not enough values to unpack (expected 4, got 3) 

If there are fewer variables than elements, you can add an asterisk * to the variable name to assign the remaining elements as a list. This is described later.

Читайте также:  Convert from xls to html

Unpack a nested tuple and list

You can also unpack a nested tuple or list. If you want to expand the inner element, enclose the variable with () or [] .

t = (0, 1, (2, 3, 4)) a, b, c = t print(a) print(b) print(c) # 0 # 1 # (2, 3, 4) print(type(c)) # a, b, (c, d, e) = t print(a) print(b) print(c) print(d) print(e) # 0 # 1 # 2 # 3 # 4 

Unpack with _ (underscore)

By convention, unnecessary values may be assigned to underscores _ in Python. It does not have a grammatical special meaning but is simply assigned to a variable named _ .

t = (0, 1, 2) a, b, _ = t print(a) print(b) print(_) # 0 # 1 # 2 

Unpack with * (asterisk)

When there are fewer variables than elements, adding an asterisk * to the variable name groups the remaining elements as a list.

It is implemented in Python 3 and cannot be used in Python 2.

The elements from the beginning and the end are assigned to variables without * , and the remaining elements are assigned as a list to variables with * .

t = (0, 1, 2, 3, 4) a, b, *c = t print(a) print(b) print(c) # 0 # 1 # [2, 3, 4] print(type(c)) # a, *b, c = t print(a) print(b) print(c) # 0 # [1, 2, 3] # 4 *a, b, c = t print(a) print(b) print(c) # [0, 1, 2] # 3 # 4 

For example, to assign only the first two elements of a tuple or a list to variables, use the underscore _ for the remaining elements.

a, b, *_ = t print(a) print(b) print(_) # 0 # 1 # [2, 3, 4] 

The same operation can be written as follows:

a, b = t[0], t[1] print(a) print(b) # 0 # 1 

You can apply * to only one variable. If multiple variables have * , the assignment of elements becomes ambiguous, resulting in a SyntaxError .

# *a, b, *c = t # SyntaxError: two starred expressions in assignment 

Note that if only one element is assigned to a variable with * , it will still be assigned as a list.

t = (0, 1, 2) a, b, *c = t print(a) print(b) print(c) # 0 # 1 # [2] print(type(c)) # 

If there are no extra elements, an empty list is assigned.

a, b, c, *d = t print(a) print(b) print(c) print(d) # 0 # 1 # 2 # [] 

Источник

Unpacking Iterables in Python

Learn different ways to unpack iterables or sequences in Python through useful examples.

Unpacking Iterables in Python

You can easily unpack sequences or iterables into various variables in python.

Table of Content

Difference between Sequences and Iterables?

A sequence is an ordered collection of values. Once a list is initialized, the index of the values will not change. Some examples of sequences are List, Dictionary, Tuples, and Strings.

Iterables are a collection of values over which you can loop over. All sequences are iterables, but not all iterables are sequences. For example, Sets.

So the order in which the values in the set are initialized is not the way it appears. Also, Sets return only unique elements.

Basic Unpacking

You can carry out the unpacking procedure for all kinds of iterables like lists, tuples, strings, iterators and generators.

There are 2 ways to unpack iterables in Python.

  1. For known length iterables — Providing the exact number of variables to unpack as the number of elements in the sequence/iterable.
  2. For arbitrary length iterables — Using star expressions (*) to unpack when you are unsure of the number of variables to pass.

Let’s look at a few examples.

Unpacking known length iterables

When the length of the data type is very obvious, you can pass in the exact number of variables as the number of values in the data type to unpack the values.

my_info = ["Lenin", "Mishra", 28, "Amsterdam"] name, surname, age, place = my_info # Result >>> name 'Lenin' >>> surname 'Mishra' >>> age 28 >>> place 'Amsterdam' 

Since I know that there are 4 values inside my list. I am passing in 4 variables to unpack those values. The values are unpacked in the same order as the provided variables.

If there is a mismatch of values and variables, Python will throw you an error.

In case when fewer variables are provided, Python will tell you that there are too many values to unpack.

Example 1

my_info = ["Lenin", "Mishra", 28, "Amsterdam"] name, other_info = my_info # Result Traceback (most recent call last): File , line 2, in name, other_info = my_info ValueError: too many values to unpack (expected 2)

In case when more variables are provided, Python will tell you that there are not enough values to unpack.

Example 2

my_info = ["Lenin", "Mishra", 28, "Amsterdam"] name, surname, age, place, other = my_info # Result Traceback (most recent call last): File , line 2, in name, surname, age, place, other = my_info ValueError: not enough values to unpack (expected 5, got 4)

Unpacking Sequence within a Sequence

Let’s look at another example. Let’s assume you provide the name and surname as a tuple (or any sequence).

my_info = [("Lenin", "Mishra"), 28, "Amsterdam"] name, age, place = my_info # Result >>> name ('Lenin', 'Mishra') >>> age 28 >>> place 'Amsterdam'

Now the name variable stores the tuple as a value with both the first name and surname as information. If we want to extract both parts of the name, we can pass in a sequence of variables.

my_info = [("Lenin", "Mishra"), 28, "Amsterdam"] (name, surname), age, place = my_info # Result >>> name 'Lenin' >>> surname 'Mishra' >>> age 28 >>> place 'Amsterdam'

How to discard values while unpacking?

It is also possible to discard certain values that you may not need while unpacking.

Let’s say you are not interested in the place information. You can use a _ to disregard the unpacked value.

my_info = ["Lenin", "Mishra", 28, "Amsterdam"] name, surname, age, _ = my_info # Result >>> name 'Lenin' >>> surname 'Mishra' >>> age 28

How to unpack a Python dictionary?

The process for unpacking a python dictionary is not the same as unpacking a python tuple or a list. When you apply the above method to a dictionary, you will be unpacking just the keys.

my_info = x, y = my_info # Result >>> x 'name' >>> y 'age'

Now to get the values for the respective dictionary keys, you have to call the dictionary key.

>>> my_info[x] 'Lenin' >>> my_info[y] 28

Unpacking arbitrary length iterables

Let’s be honest! It’s not always possible to provide all the required variables to unpack the values. Imagine providing a million variables to unpack a list containing 1000 records! That is just sloppy.

Let’s look at an example. Suppose you have a list of university scores from the 1st to the 6th semester. While averaging, you decide to leave out the first and last score.

In this case, you need to unpack all the scores between the first and last values.

scores = [92, 90, 87, 64, 75, 91] first, *middle, last = scores >>> middle [90, 87, 64, 75]

Let’s look at a log message. To learn more about Logging in Python, check out this article.

What we want to achieve is get the logging level and the logging message .

log_msg = "2019-06-05 17:43:07,889 :: __main__ :: INFO :: I am a separate Logger" log_msg_comps = [x.strip() for x in log_msg.split('::')] t_stamp, file, *req_entities = log_msg_comps >>> req_entities ['INFO', 'I am a separate Logger']

The use of star expression (*) makes unpacking very convenient for arbitrary length iterables. Imagine reading a file in Python and you want to ignore the headers. You can apply a similar technique as above.

You can also discard irrelevant values by using the _ with the star expression (*) .

log_msg = "2019-06-05 17:43:07,889 :: __main__ :: INFO :: I am a separate Logger" log_msg_comps = [x.strip() for x in log_msg.split('::')] # Ignore all values except the message *_, log_message = log_msg_comps >>> log_message I am a separate Logger

How to skip header in a CSV in Python?

You can use the above unpacking techniques to skip the header of a CSV in Python.

Let’s assume a CSV file called students.csv with the following contents.

name, weight Lenin, 85 Sam, 65 Neha, 43 Abhi, 95 

You can get rid of the header 2 ways.

Method 1

import csv with open('students.csv', 'r') as input: data = csv.reader(input) header, *rows = data print(header) print(rows) 
['name', ' weight'] [['Lenin', ' 85'], ['Sam', ' 65'], ['Neha', ' 43'], ['Abhi', ' 95']] 

By using this approach, you store the header in a variable for use later. You don’t entirely ignore it.

The rest of the rows are neatly stored in the rows variable.

Method 2

You can also completely ignore the header. For this purpose, use the _ symbol.

import csv with open('students.csv', 'r') as input: data = csv.reader(input) _, *rows = data print(rows) 
[['Lenin', ' 85'], ['Sam', ' 65'], ['Neha', ' 43'], ['Abhi', ' 95']] 

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.

Источник

How to Unpack a List in Python

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 = colorsCode 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)
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 them to a variable. For example:

colors = ['red', 'blue', 'green'] red, blue, *other = colors print(red) print(blue) print(other) Code language: Python (python)
red blue ['green']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.

colors = ['cyan', 'magenta', 'yellow', 'black'] cyan, magenta, *other = colors print(cyan) print(magenta) print(other) Code language: Python (python)
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.

Источник

Оцените статью