Chuyển tới nội dung
Home » Tuple Unpacking Python 3 | What Is A Tuple In Python

Tuple Unpacking Python 3 | What Is A Tuple In Python

Unpacking a Tuple in Python

Using * Unpacking Method

You can use unpack operator * on a tuple to extract the individual elements from a tuple and assign its elements to a list by enclosing the tuple in square brackets

[]

and separating the elements with

commas

. For example, use the operator to unpack the elements of the

tuples

and assign them to the list

list1

. The resulting list contains the same elements as the original tuple, in the same order.


# Using * unpacking method tuples = ('Spark', 'Python', 'pandas', 'Java') # convert tuple into list list1 = [*tuples,] print(list1) # Output # ['Spark', 'Python', 'pandas', 'Java']

Unpacking Tuples as Dictionary

To unpack a tuple as a dictionary, you can use the

dict()

constructor along with the

zip()

function to create a dictionary from the key-value pairs generated by the

zip()

function.

For example, let’s take tuple with three elements, and create a dictionary

dictionary

with keys

courses

,

fees

, and

duration

corresponding to the elements of the tuple. First, use the

zip()

function to create a sequence of key-value pairs by matching each element of the tuple with a corresponding key. Then, you use the

dict()

constructor to convert the sequence of key-value pairs into a dictionary.


# Unpacking tuples as dictionary tuples = ('Python', '50days', 25000) dictionary = dict(zip(('courses', 'duration', 'fees'), tuples)) print(dictionary) # Output # {'courses': 'Python', 'duration': '50days', 'fees': 25000}

Follow the other example of unpacking a tuple as a dictionary object.


# Unpacking tuples as dictionary object tuples = ('Python', '50days', 25000) dictionary = {} dictionary['courses'],dictionary['duration'],dictionary['fees'] = tuples print(dictionary) # Output # {'courses': 'Python', 'duration': '50days', 'fees': 25000}

Unpacking a Tuple in Python
Unpacking a Tuple in Python

5.More on Conditions¶

The conditions used in

while

and

if

statements can contain any
operators, not just comparisons.

The comparison operators

in

and

not in

are membership tests that
determine whether a value is in (or not in) a container. The operators

is

and

is not

compare whether two objects are really the same object. All
comparison operators have the same priority, which is lower than that of all
numerical operators.

Comparisons can be chained. For example,

a < b == c

tests whether is
less than and moreover equals .

Comparisons may be combined using the Boolean operators

and

and

or

, and
the outcome of a comparison (or of any other Boolean expression) may be negated
with

not

. These have lower priorities than comparison operators; between
them,

not

has the highest priority and

or

the lowest, so that

A and
not B or C

is equivalent to

(A and (not B)) or C

. As always, parentheses
can be used to express the desired composition.

The Boolean operators

and

and

or

are so-called short-circuit
operators: their arguments are evaluated from left to right, and evaluation
stops as soon as the outcome is determined. For example, if and are
true but is false,

A and B and C

does not evaluate the expression
. When used as a general value and not as a Boolean, the return value of a
short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

>>> string1, string2, string3 = ”, ‘Trondheim’, ‘Hammer Dance’ >>> non_null = string1 or string2 or string3 >>> non_null ‘Trondheim’

Note that in Python, unlike C, assignment inside expressions must be done
explicitly with the
walrus operator

:=

.
This avoids a common class of problems encountered in C programs: typing
in an expression when

==

was intended.

Using Asterisk

If the number of variables is less than the number of values, you can add an to the variable name and the
values will be assigned to the variable as a list:

Example

Assign the rest of the values as a list called “red”:

(green, yellow, *red) = fruits

print(green)

print(yellow)

print(red)

If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.

Example

Add a list of values the “tropic” variable:

(green, *tropic, red) = fruits

print(green)

print(tropic)

print(red)

In Python, Tuple unpacking is a feature that allows us to assign values to multiple variables in a single statement. It works by unpacking a sequence (e.g., a tuple, list, or string) into individual variables. Unpacking is not limited to tuples, you can also use it to unpack lists, strings, and other iterable objects. Unpacking is a powerful feature in Python that can make your code more concise and readable.

You can unpack tuples in Python by using many ways, for example, using the unpacking,

dictionary

,

lambda

, and

list comprehension

. In this article, I will explain tuple unpacking by using all these methods with examples.

Related: In Python, you can also unpack the list.

Tuple Unpacking in Python | Multiple Assignment in Python
Tuple Unpacking in Python | Multiple Assignment in Python

13.3.The Pythonic Way to Enumerate Items in a Sequence¶

When we first introduced the for loop, we provided an example of how to iterate through the indexes of a sequence, and thus enumerate the items and their positions in the sequence.

We are now prepared to understand a more pythonic approach to enumerating items in a sequence. Python provides a built-in function

enumerate

. It takes a sequence as input and returns a sequence of tuples. In each tuple, the first element is an integer and the second is an item from the original sequence. (It actually produces an “iterable” rather than a list, but we can use it in a for loop as the sequence to iterate over.)

The pythonic way to consume the results of enumerate, however, is to unpack the tuples while iterating through them, so that the code is easier to understand.

Check your Understanding

With only one line of code, assign the variables

water

,

fire

,

electric

, and

grass

to the values “Squirtle”, “Charmander”, “Pikachu”, and “Bulbasaur”

With only one line of code, assign four variables,

v1

,

v2

,

v3

, and

v4

, to the following four values: 1, 2, 3, 4.

If you remember, the .items() dictionary method produces a sequence of tuples. Keeping this in mind, we have provided you a dictionary called

pokemon

. For every key value pair, append the key to the list

p_names

, and append the value to the list

p_number

. Do not use the .keys() or .values() methods.

The .items() method produces a sequence of key-value pair tuples. With this in mind, write code to create a list of keys from the dictionary

track_medal_counts

and assign the list to the variable name

track_events

. Do NOT use the .keys() method.

Summary: in this tutorial, you’ll learn how to unpack tuples in Python.

Related Articles

  • Python Tuple Access with Example
  • Add Element to Tuple in Python
  • Add Elements of Tuples in Python
  • Append Element to a Tuple in Python
  • Python Empty Tuple with Examples
  • Python Tuple Slice with Examples
  • Python Tuple Length with Example
  • How to Sort List of Tuples in Python
  • Remove Last Element from Tuple in Python
  • Tuple as Dictionary Key in Python

This Article is going to clarify different ways to unpack a Tuple, following certain examples on our code snippet. Let’s get into it without wasting time.

Before getting started, First of all, Let’s understand what a Tuple is in python.

A tuple is one of the four popular in-built collections in Python among List, Set, and Dictionary. It is used to store ordered, indexed collection of data irrespective of datatypes.

Similar to Arrays, the first value in the Tuple will have the index [0], the second value [1], and so on. A Tuple can be created by following commands.

new_tuple = (“New Delhi”, “Tiger”, 5000, “5.285”, “Rahul”, True)

Our new_tuple will be created as follows.

print(new_tuple) (‘New Delhi’, ‘Tiger’, 5000, ‘5.285’, ‘Rahul’, True)

Some key features of a Tuple in Python are as follows.

  • It’s immutable in nature. Once a Tuple is created, it is neither possible to modify its elements nor to delete.
  • Deleting an element from a Tuple is not possible. But deleting a Tuple is.
  • Tuples can store duplicate values.
  • We can create an empty Tuple.
  • We can create a Tuple with a single element.
  • Concatenation is possible in between two or more Tuples.
  • Tuples do not support resizing methods:

    append(), remove(), pop()

    etc.

As you know A Tuple is immutable in nature. Its values or contents can not be changed once created. But one thing we can do is, We can unpack the contents of a Tuple. Unpacking a Tuple means splitting the Tuple’s contents into individual variables. We are going to learn here three methods to do the same followed by some examples. Let’s understand them as well.

Unpacking a Python Tuple By Reassigning

#Let’s create a tuple new_tuple = (“New Delhi”, “Tiger”, 5000, “5.285”, “Rahul”, True) #We can unpack the tuple by assigning each content of the tuple to individual variables (a, b, c, d, e, f) = new_tuple

In the above example, We assigned each content of the Tuple to individual variables. Let’s see the contents of each variable by following the code snippet.

#printing each variable print(a) ‘New Delhi’ print(b) ‘Tiger’ print(c) 5000 print(d) ‘5.285’ print(e) Rahul print(f) True

While using this method, We must remember that We need to take the no. of variables the same as the no. of contents inside the Tuple. otherwise, it will throw errors as follows.

(a, b, c, d) = new_tuple Traceback (most recent call last): File ” “, line 1, in

(a, b, c, d) = new_tuple ValueError: too many values to unpack (expected 4)

Unpacking a Tuple Using the Asterisk * sign

In this example, We are going to use the Asterisk

(*)

operator. If the number of variables is less than the number of contents inside our Tuple, We can add a to the variable name and the values will be assigned to the variable as a list. Let’s try this as the following code snippet.

#taking the same tuple created in method 1 print(new_tuple) (‘New Delhi’, ‘Tiger’, 5000, ‘5.285’, ‘Rahul’, True) #no. of variables (=3) is less than no. of contents (=6). #adding * to y (x, *y, z) = new_tuple

Now, We can see the result by printing the variables individually.

print(x) New Delhi print(y) [‘Tiger’, 5000, ‘5.285’, ‘Rahul’] print(z) True

We can see that the four contents in between created a list and assigned to y. In this way, This method works. We can understand better by following the below examples in our code snippet.

#Example 1 (x, y, *z) = new_tuple print(x) ‘New Delhi’ print(y) ‘Tiger’ print(z) [5000, ‘5.285’, ‘Rahul’, True] #Example 2 (*x, y, z) = new_tuple print(x) [‘New Delhi’, ‘Tiger’, 5000, ‘5.285’] print(y) ‘Rahul’ print(z) True #Example 3 (x, y, *z, w) = new_tuple print(x) New Delhi print(z) [5000, ‘5.285’, ‘Rahul’] print(w) True print(y) Tiger

Note: While using this method, add the * operator to a single variable only. Else, it will throw an error as follow.

(*x, *y, z) = new_tuple SyntaxError: multiple starred expressions in assignment

Tuples & Tuple Unpacking in Python
Tuples & Tuple Unpacking in Python

5.Sets¶

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the

set()

function can be used to create sets. Note: to
create an empty set you have to use

set()

, not

{}

; the latter creates an
empty dictionary, a data structure that we discuss in the next section.

Here is a brief demonstration:

>>> basket = {‘apple’, ‘orange’, ‘apple’, ‘pear’, ‘orange’, ‘banana’} >>> print(basket) # show that duplicates have been removed {‘orange’, ‘banana’, ‘pear’, ‘apple’} >>> ‘orange’ in basket # fast membership testing True >>> ‘crabgrass’ in basket False >>> # Demonstrate set operations on unique letters from two words … >>> a = set(‘abracadabra’) >>> b = set(‘alacazam’) >>> a # unique letters in a {‘a’, ‘r’, ‘b’, ‘c’, ‘d’} >>> a – b # letters in a but not in b {‘r’, ‘d’, ‘b’} >>> a | b # letters in a or b or both {‘a’, ‘c’, ‘r’, ‘d’, ‘b’, ‘m’, ‘z’, ‘l’} >>> a & b # letters in both a and b {‘a’, ‘c’} >>> a ^ b # letters in a or b but not both {‘r’, ‘d’, ‘b’, ‘m’, ‘z’, ‘l’}

Similarly to list comprehensions, set comprehensions are also supported:

>>> a = {x for x in ‘abracadabra’ if x not in ‘abc’} >>> a {‘r’, ‘d’}

Unpacking Tuples as Dictionary

To unpack a tuple as a dictionary, you can use the

dict()

constructor along with the

zip()

function to create a dictionary from the key-value pairs generated by the

zip()

function.

For example, let’s take tuple with three elements, and create a dictionary

dictionary

with keys

courses

,

fees

, and

duration

corresponding to the elements of the tuple. First, use the

zip()

function to create a sequence of key-value pairs by matching each element of the tuple with a corresponding key. Then, you use the

dict()

constructor to convert the sequence of key-value pairs into a dictionary.


# Unpacking tuples as dictionary tuples = ('Python', '50days', 25000) dictionary = dict(zip(('courses', 'duration', 'fees'), tuples)) print(dictionary) # Output # {'courses': 'Python', 'duration': '50days', 'fees': 25000}

Follow the other example of unpacking a tuple as a dictionary object.


# Unpacking tuples as dictionary object tuples = ('Python', '50days', 25000) dictionary = {} dictionary['courses'],dictionary['duration'],dictionary['fees'] = tuples print(dictionary) # Output # {'courses': 'Python', 'duration': '50days', 'fees': 25000}

Tuple Packing and Unpacking in Python | Python Tutorial | Skillslash
Tuple Packing and Unpacking in Python | Python Tutorial | Skillslash

Unpacking Tuples Using Lambda Function

You can also use a

lambda

function to unpack tuples in Python. For example, you define a lambda function that takes two arguments and , and returns their sum. Use the operator to unpack the tuple and pass their contents as arguments to the

lambda

function. The result is the sum of the two values in the tuple, which is

15

.


# Unpacking tuples using lambda function tuples = (5, 10) result = (lambda x,y: x + y)(*tuples) print(result) # Output # 15

ValueError: too many values to unpack

The following example unpacks the elements of a tuple into variables. However, it’ll result in an error:


x, y = 10, 20, 30

Code language: Python (python)

Error:


ValueError: too many values to unpack (expected 2)

Code language: Python (python)

This error is because the right-hand side returns three values while the left-hand side only has two variables.

To fix this, you can add a variable:


x, y, _ = 10, 20, 30

Code language: Python (python)

The variable is a regular variable in Python. By convention, it’s called a dummy variable.

Typically, you use the dummy variable to unpack when you don’t care and use its value afterward.

How to Pack and Unpack a Tuple in Python? (+ ValueError) - Python Tutorial for Beginners
How to Pack and Unpack a Tuple in Python? (+ ValueError) – Python Tutorial for Beginners

Unpacking a Tuple in Python

Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program.

Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable.

Example 1

Quick Examples of Tuple Unpacking

If you are in a hurry, below are some quick examples of Python tuple unpacking.


# Quick examples of tuple unpacking # Example 1: Using * unpacking method tuples = ('Spark', 'Python', 'pandas', 'Java') list1 = [*tuples,] # Example 2: Unpacking tuples as arguments def technology(courses, fees, duration): print(courses) print(fees) print(duration) tuples = ('Python', 25000, '50days') technology(*tuples) # Example 3: Unpacking tuples as a dictionary tuples = ('Python', '50days', 25000) dictionary = dict(zip(('courses', 'duration', 'fees'), tuples)) # Example 4: Unpacking tuples as a dictionary object tuples = ('Python', '50days', 25000) dictionary = {} dictionary['courses'],dictionary['duration'],dictionary['fees'] = tuples # Example 5: Unpacking tuples using lambda function tuples = (5, 10) result = (lambda x,y: x + y)(*tuples) # Example 6: Unpacking nested tuples # Using list comprehension nested_tuple = ((2, 4), (6, 8), (10, 12)) result = [x + y for x, y in nested_tuple] # Example 7: Using list comprehension tuples = ((1, 3, 5), (7, 9, 11), (13, 15, 17)) result = [(x,y,z) for x,y,z in tuples]

Tuple unpacking in Python 3 Coding for Kids Python Learn to Code with 50 Awesome Games an Activities
Tuple unpacking in Python 3 Coding for Kids Python Learn to Code with 50 Awesome Games an Activities

Unpacking Tuple as Arguments

You can unpack tuple and pass the elements of a tuple as arguments to a function in Python. This is a convenient way to pass multiple arguments to a function without having to manually specify each argument.

For example, In the below code snippet we define a function

technology

that takes three arguments

courses

,

fees

, and

duration

. And, create a tuple

tuples

with three elements and use tuple unpacking with the operator to pass the elements of the tuple as arguments to the function.


# Unpacking tuple as arguments def technology(courses, fees, duration): print(courses) print(fees) print(duration) tuples = ('Python', 25000, '50days') technology(*tuples) # Output # Python # 25000 # 50days

Python3


def


rear_element_extraction(test_list, res


[]):


if


not


test_list:


return


res


res.append(test_list[


][


])


return


rear_element_extraction(test_list[


:], res)


test_list


[(


'Rash'


21


), (


'Varsha'


20


), (


'Kil'


19


)]


print


"The original list is : "


str


(test_list))


res


rear_element_extraction(test_list)


print


"List with only rear tuple element : "


str


(res))

Output

The original list is : [(1, ‘Rash’, 21), (2, ‘Varsha’, 20), (3, ‘Kil’, 19)]
List with only rear tuple element : [21, 20, 19]

Time Complexity: O(n)Auxiliary Space: O(n)

Method#4:Using enumerate

Approach:

  1. Initialize a list of tuples test_list.
  2. Print the original list test_list.
  3. Use enumerate() to get the index and tuple of each record in test_list.
  4. For each tuple in test_list, iterate over its elements using range() and select the last element using its index.
  5. Append the selected element to a new list res.
  6. Print the final list res.

Below is the implementation of the above approach:

Functions in Python are easy 📞
Functions in Python are easy 📞

Unpack a nested tuple and list

You can also unpack a nested tuple or list. If you want to unpack the inner elements, 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

Python3


def


result(x, y):


return


print


(result(


10


100


))


10


100


print


(result(


z))

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
24 Jun, 2021

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Python – Unpack Tuples

Python Tuples | Python Tuples Tutorial | Python Tutorial | Python Programming | Simplilearn
Python Tuples | Python Tuples Tutorial | Python Tutorial | Python Programming | Simplilearn

Conclusion

In this article, We covered how to unpack a Tuple in Python. Tuples are of advantage when used for the use case it is designed for like other elements in Python. Hope You must have enjoyed it. We must visit again with some more exciting topics.

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 information on unpacking lists, tuples, and dictionaries (

dict

) as arguments in a function using (asterisk).

Python3


test_list


[(


'Rash'


21


), (


'Varsha'


20


), (


'Kil'


19


)]


print


"The original list is: "


str


(test_list))


res


[]


for


tup


in


test_list:


res.append(tup[


])


print


"List with only rear tuple element: "


str


(res))

Output

The original list is: [(1, ‘Rash’, 21), (2, ‘Varsha’, 20), (3, ‘Kil’, 19)]
List with only rear tuple element: [21, 20, 19]

Time complexity: O(n) where n is the length of the input listAuxiliary space: O(n) where n is the length of the input list, for the output list.

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
08 May, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Data Structures¶

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

learning AI and ChatGPT isn’t that hard
learning AI and ChatGPT isn’t that hard

5.More on Lists¶

The list data type has some more methods. Here are all of the methods of list objects:

list.append(x)

Add an item to the end of the list. Equivalent to


a[len(a):] = [x]

.

list.extend(iterable)

Extend the list by appending all the items from the iterable. Equivalent to


a[len(a):] = iterable

.

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so


a.insert(0, x)

inserts at the front of the list, and

a.insert(len(a), x)

is equivalent to

a.append(x)

.

list.remove(x)

Remove the first item from the list whose value is equal to x. It raises a


ValueError

if there is no such item.

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified,


a.pop()

removes and returns the last item in the list. It raises an

IndexError

if the list is empty or the index is outside the list range.

list.clear()

Remove all items from the list. Equivalent to


del a[:]

.

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a


ValueError

if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

list.count(x)

Return the number of times x appears in the list.

list.sort(*, key=None, reverse=False)

Sort the items of the list in place (the arguments can be used for sort customization, see


sorted()

for their explanation).

list.reverse()

Reverse the elements of the list in place.

list.copy()

Return a shallow copy of the list. Equivalent to


a[:]

.

An example that uses most of the list methods:

>>> fruits = [‘orange’, ‘apple’, ‘pear’, ‘banana’, ‘kiwi’, ‘apple’, ‘banana’] >>> fruits.count(‘apple’) 2 >>> fruits.count(‘tangerine’) 0 >>> fruits.index(‘banana’) 3 >>> fruits.index(‘banana’, 4) # Find next banana starting at position 4 6 >>> fruits.reverse() >>> fruits [‘banana’, ‘apple’, ‘kiwi’, ‘banana’, ‘pear’, ‘apple’, ‘orange’] >>> fruits.append(‘grape’) >>> fruits [‘banana’, ‘apple’, ‘kiwi’, ‘banana’, ‘pear’, ‘apple’, ‘orange’, ‘grape’] >>> fruits.sort() >>> fruits [‘apple’, ‘apple’, ‘banana’, ‘banana’, ‘grape’, ‘kiwi’, ‘orange’, ‘pear’] >>> fruits.pop() ‘pear’

You might have noticed that methods like

insert

,

remove

or

sort

that
only modify the list have no return value printed – they return the default

None

. [1] This is a design principle for all mutable data structures in
Python.

Another thing you might notice is that not all data can be sorted or
compared. For instance,

[None, 'hello', 10]

doesn’t sort because
integers can’t be compared to strings and None can’t be compared to
other types. Also, there are some types that don’t have a defined
ordering relation. For example,

3+4j < 5+7j

isn’t a valid
comparison.

5.1.Using Lists as Stacks¶

The list methods make it very easy to use a list as a stack, where the last
element added is the first element retrieved (“last-in, first-out”). To add an
item to the top of the stack, use

append()

. To retrieve an item from the
top of the stack, use

pop()

without an explicit index. For example:

>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4]

5.1.Using Lists as Queues¶

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use

collections.deque

which was designed to
have fast appends and pops from both ends. For example:

>>> from collections import deque >>> queue = deque([“Eric”, “John”, “Michael”]) >>> queue.append(“Terry”) # Terry arrives >>> queue.append(“Graham”) # Graham arrives >>> queue.popleft() # The first to arrive now leaves ‘Eric’ >>> queue.popleft() # The second to arrive now leaves ‘John’ >>> queue # Remaining queue in order of arrival deque([‘Michael’, ‘Terry’, ‘Graham’])

5.1.List Comprehensions¶

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

>>> squares = [] >>> for x in range(10): … squares.append(x**2) … >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note that this creates (or overwrites) a variable named that still exists
after the loop completes. We can calculate the list of squares without any
side effects using:

squares = list(map(lambda x: x**2, range(10)))

or, equivalently:

squares = [x**2 for x in range(10)]

which is more concise and readable.

A list comprehension consists of brackets containing an expression followed
by a

for

clause, then zero or more

for

or

if

clauses. The result will be a new list resulting from evaluating the expression
in the context of the

for

and

if

clauses which follow it.
For example, this listcomp combines the elements of two lists if they are not
equal:

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and it’s equivalent to:

>>> combs = [] >>> for x in [1,2,3]: … for y in [3,1,4]: … if x != y: … combs.append((x, y)) … >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Note how the order of the

for

and

if

statements is the
same in both these snippets.

If the expression is a tuple (e.g. the

(x, y)

in the previous example),
it must be parenthesized.

>>> vec = [-4, -2, 0, 2, 4] >>> # create a new list with the values doubled >>> [x*2 for x in vec] [-8, -4, 0, 4, 8] >>> # filter the list to exclude negative numbers >>> [x for x in vec if x >= 0] [0, 2, 4] >>> # apply a function to all the elements >>> [abs(x) for x in vec] [4, 2, 0, 2, 4] >>> # call a method on each element >>> freshfruit = [‘ banana’, ‘ loganberry ‘, ‘passion fruit ‘] >>> [weapon.strip() for weapon in freshfruit] [‘banana’, ‘loganberry’, ‘passion fruit’] >>> # create a list of 2-tuples like (number, square) >>> [(x, x**2) for x in range(6)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] >>> # the tuple must be parenthesized, otherwise an error is raised >>> [x, x**2 for x in range(6)] File ”

“, line 1 [x, x**2 for x in range(6)] ^^^^^^^ SyntaxError: did you forget parentheses around the comprehension target? >>> # flatten a list using a listcomp with two ‘for’ >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehensions can contain complex expressions and nested functions:

>>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] [‘3.1’, ‘3.14’, ‘3.142’, ‘3.1416’, ‘3.14159’]

5.1.Nested List Comprehensions¶

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Consider the following example of a 3×4 matrix implemented as a list of 3 lists of length 4:

>>> matrix = [ … [1, 2, 3, 4], … [5, 6, 7, 8], … [9, 10, 11, 12], … ]

The following list comprehension will transpose rows and columns:

>>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As we saw in the previous section, the inner list comprehension is evaluated in
the context of the

for

that follows it, so this example is
equivalent to:

>>> transposed = [] >>> for i in range(4): … transposed.append([row[i] for row in matrix]) … >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

which, in turn, is the same as:

>>> transposed = [] >>> for i in range(4): … # the following 3 lines implement the nested listcomp … transposed_row = [] … for row in matrix: … transposed_row.append(row[i]) … transposed.append(transposed_row) … >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

In the real world, you should prefer built-in functions to complex flow statements.
The

zip()

function would do a great job for this use case:

>>> list(zip(*matrix)) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

See Unpacking Argument Lists for details on the asterisk in this line.

Python3


import


numpy as np


test_list


[(


'Rash'


21


), (


'Varsha'


20


), (


'Kil'


19


)]


print


"The original list is : "


str


(test_list))


arr


np.array(test_list)


res


arr[:,


print


"List with only rear tuple element : "


str


(res))

Output:

The original list is : [(1, ‘Rash’, 21), (2, ‘Varsha’, 20), (3, ‘Kil’, 19)]
List with only rear tuple element : [’21’ ’20’ ’19’]

Time complexity: O(n), where n is the number of tuples in the input list. The numpy array conversion takes O(n) time, and slicing takes constant time.Space complexity: O(n), where n is the number of tuples in the input list. This is because the input list is converted to a numpy array which takes O(n) space, and the resulting array containing only the last elements of each tuple also takes O(n) space.

Method #6: Using a for loop

Step-by-step approach:

  1. Initialize a list of tuples called test_list
  2. Print the original list using the print() function
  3. Create an empty list called res to store the extracted elements
  4. Use a for loop to iterate over each tuple in test_list

    • Extract the last element (which has index -1) and append it to res
  5. Print the result using the print() function.

Below is the implementation of the above approach:

List Comprehension - BEST Python feature !!! Fast and Efficient
List Comprehension – BEST Python feature !!! Fast and Efficient

Summary

  • Python uses the commas () to define a tuple, not parentheses.
  • Unpacking tuples means assigning individual elements of a tuple to multiple variables.
  • Use the operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

In Python, Tuple unpacking is a feature that allows us to assign values to multiple variables in a single statement. It works by unpacking a sequence (e.g., a tuple, list, or string) into individual variables. Unpacking is not limited to tuples, you can also use it to unpack lists, strings, and other iterable objects. Unpacking is a powerful feature in Python that can make your code more concise and readable.

You can unpack tuples in Python by using many ways, for example, using the unpacking,

dictionary

,

lambda

, and

list comprehension

. In this article, I will explain tuple unpacking by using all these methods with examples.

Related: In Python, you can also unpack the list.

Quick Examples of Tuple Unpacking

If you are in a hurry, below are some quick examples of Python tuple unpacking.


# Quick examples of tuple unpacking # Example 1: Using * unpacking method tuples = ('Spark', 'Python', 'pandas', 'Java') list1 = [*tuples,] # Example 2: Unpacking tuples as arguments def technology(courses, fees, duration): print(courses) print(fees) print(duration) tuples = ('Python', 25000, '50days') technology(*tuples) # Example 3: Unpacking tuples as a dictionary tuples = ('Python', '50days', 25000) dictionary = dict(zip(('courses', 'duration', 'fees'), tuples)) # Example 4: Unpacking tuples as a dictionary object tuples = ('Python', '50days', 25000) dictionary = {} dictionary['courses'],dictionary['duration'],dictionary['fees'] = tuples # Example 5: Unpacking tuples using lambda function tuples = (5, 10) result = (lambda x,y: x + y)(*tuples) # Example 6: Unpacking nested tuples # Using list comprehension nested_tuple = ((2, 4), (6, 8), (10, 12)) result = [x + y for x, y in nested_tuple] # Example 7: Using list comprehension tuples = ((1, 3, 5), (7, 9, 11), (13, 15, 17)) result = [(x,y,z) for x,y,z in tuples]

[Khóa học lập trình Python cơ bản] - Bài 14: Tuple trong Python | HowKteam
[Khóa học lập trình Python cơ bản] – Bài 14: Tuple trong Python | HowKteam

Python3


test_list


[(


'Rash'


21


), (


'Varsha'


20


), (


'Kil'


19


)]


print


"The original list is : "


str


(test_list))


res


[lis[


for


lis


in


test_list]


print


"List with only rear tuple element : "


str


(res))

Output :

The original list is : [(1, ‘Rash’, 21), (2, ‘Varsha’, 20), (3, ‘Kil’, 19)]
List with only rear tuple element : [21, 20, 19]

Time complexity: O(n), where n is the number of tuples in the list.Auxiliary space: O(n), as we are creating a new list to store the extracted elements.

Method #2: Using map() + itemgetter()

map() coupled with itemgetter() can perform this task in simpler way. map() maps all the element we access using itemgetter() and returns the result.

Follow the below steps to implement the above idea:

  1. Importing the itemgetter module from the operator library.
  2. Initializing a list of tuples test_list that contains three tuples, where each tuple represents a record containing three elements: an integer value, a string value, and another integer value.
  3. Printing the original list using the print() function, which will display the list of tuples on the console.
  4. Using the map() function with the itemgetter() function to extract the last element of each tuple in the test_list. The itemgetter(-1) function is used as a key function to extract the last element of each tuple.
  5. Converting the output of the map() function to a list using the list() function.
  6. Assigning the extracted last elements to a new list named res.
  7. Printing the res list, which contains only the last element of each tuple in the test_list. This will display the extracted last elements of each tuple on the console.

Below is the implementation of the above approach:

5.Looping Techniques¶

When looping through dictionaries, the key and corresponding value can be
retrieved at the same time using the

items()

method.

>>> knights = {‘gallahad’: ‘the pure’, ‘robin’: ‘the brave’} >>> for k, v in knights.items(): … print(k, v) … gallahad the pure robin the brave

When looping through a sequence, the position index and corresponding value can
be retrieved at the same time using the

enumerate()

function.

>>> for i, v in enumerate([‘tic’, ‘tac’, ‘toe’]): … print(i, v) … 0 tic 1 tac 2 toe

To loop over two or more sequences at the same time, the entries can be paired
with the

zip()

function.

>>> questions = [‘name’, ‘quest’, ‘favorite color’] >>> answers = [‘lancelot’, ‘the holy grail’, ‘blue’] >>> for q, a in zip(questions, answers): … print(‘What is your {0}? It is {1}.’.format(q, a)) … What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.

To loop over a sequence in reverse, first specify the sequence in a forward
direction and then call the

reversed()

function.

>>> for i in reversed(range(1, 10, 2)): … print(i) … 9 7 5 3 1

To loop over a sequence in sorted order, use the

sorted()

function which
returns a new sorted list while leaving the source unaltered.

>>> basket = [‘apple’, ‘orange’, ‘apple’, ‘pear’, ‘orange’, ‘banana’] >>> for i in sorted(basket): … print(i) … apple apple banana orange orange pear

Using

set()

on a sequence eliminates duplicate elements. The use of

sorted()

in combination with

set()

over a sequence is an idiomatic
way to loop over unique elements of the sequence in sorted order.

>>> basket = [‘apple’, ‘orange’, ‘apple’, ‘pear’, ‘orange’, ‘banana’] >>> for f in sorted(set(basket)): … print(f) … apple banana orange pear

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

>>> import math >>> raw_data = [56.2, float(‘NaN’), 51.7, 55.3, 52.5, float(‘NaN’), 47.8] >>> filtered_data = [] >>> for value in raw_data: … if not math.isnan(value): … filtered_data.append(value) … >>> filtered_data [56.2, 51.7, 55.3, 52.5, 47.8]

Python tuples 📋
Python tuples 📋

Python3


x,


y, z


10


"Geeks "


" for "


"Geeks "


50


print


(x)


print


(y)


print


(z)


x, y,


10


"Geeks "


" for "


"Geeks "


50


print


(x)


print


(y)


print


(z)

Output:

10
[‘Geeks ‘, ‘ for ‘, ‘Geeks ‘]
50
10
Geeks
[‘ for ‘, ‘Geeks ‘, 50]

In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable. Consider the following code for better understanding.

Example 3 :

Unpacking a Tuple

When we create a tuple, we normally assign values to it. This is called “packing” a tuple:

Example

Packing a tuple:

But, in Python, we are also allowed to extract the values back into variables. This is called “unpacking”:

Example

Unpacking a tuple:

(green, yellow, red) = fruits

print(green)

print(yellow)

print(red)

Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.

Python Tuples  ||  Python Tutorial  ||  Learn Python Programming
Python Tuples || Python Tutorial || Learn Python Programming

Python3


"MNNIT Allahabad"


5000


"Engineering"


(college, student, type_ofcollege)


print


(college)


print


(student)


print


(type_ofcollege)

Output:

MNNIT Allahabad
5000
Engineering

NOTE : In unpacking of tuple number of variables on left-hand side should be equal to number of values in given tuple a.Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that there can be many number of arguments in place of (*args) in python. All values will be assigned to every variable on the left-hand side and all remaining values will be assigned to *args .For better understanding consider the following code.

Example 2

Python3


from


operator


import


itemgetter


test_list


[(


'Rash'


21


), (


'Varsha'


20


), (


'Kil'


19


)]


print


"The original list is : "


str


(test_list))


res


list


map


(itemgetter(


), test_list))


print


"List with only rear tuple element : "


str


(res))

Output :

The original list is : [(1, ‘Rash’, 21), (2, ‘Varsha’, 20), (3, ‘Kil’, 19)]
List with only rear tuple element : [21, 20, 19]

Time complexity: O(n), where n is the length of the input list test_list.Auxiliary space: O(n), where n is the length of the input list test_list.

Method#3: Using the Recursive method.

Tuples in Python - Advanced Python 02 - Programming Tutorial
Tuples in Python – Advanced Python 02 – Programming Tutorial

Unpacking Tuple as Arguments

You can unpack tuple and pass the elements of a tuple as arguments to a function in Python. This is a convenient way to pass multiple arguments to a function without having to manually specify each argument.

For example, In the below code snippet we define a function

technology

that takes three arguments

courses

,

fees

, and

duration

. And, create a tuple

tuples

with three elements and use tuple unpacking with the operator to pass the elements of the tuple as arguments to the function.


# Unpacking tuple as arguments def technology(courses, fees, duration): print(courses) print(fees) print(duration) tuples = ('Python', 25000, '50days') technology(*tuples) # Output # Python # 25000 # 50days

What Is a Tuple in Python

In Python, a tuple is one of the basic built-in types. Similar to a list, a tuple can store elements of different kinds.

The main difference between a tuple and a list in Python is that a tuple is immutable, whereas a list is mutable. This means you cannot change the tuple in any way after it has been created.

For example, here is a tuple of three integers:

nums = (1, 2, 3)

It is worthwhile to notice right from the get-go that a tuple does not necessarily need parenthesis.

For example, you can create the same tuple as above with:

nums = 1, 2, 3

To learn more about tuples in Python, feel free to check this article.

Tuples | Python Tutorial
Tuples | Python Tutorial

5.Dictionaries¶

Another useful data type built into Python is the dictionary (see
Mapping Types — dict). Dictionaries are sometimes found in other languages as
“associative memories” or “associative arrays”. Unlike sequences, which are
indexed by a range of numbers, dictionaries are indexed by keys, which can be
any immutable type; strings and numbers can always be keys. Tuples can be used
as keys if they contain only strings, numbers, or tuples; if a tuple contains
any mutable object either directly or indirectly, it cannot be used as a key.
You can’t use lists as keys, since lists can be modified in place using index
assignments, slice assignments, or methods like

append()

and

extend()

.

It is best to think of a dictionary as a set of key: value pairs,
with the requirement that the keys are unique (within one dictionary). A pair of
braces creates an empty dictionary:

{}

. Placing a comma-separated list of
key:value pairs within the braces adds initial key:value pairs to the
dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and
extracting the value given the key. It is also possible to delete a key:value
pair with

del

. If you store using a key that is already in use, the old
value associated with that key is forgotten. It is an error to extract a value
using a non-existent key.

Performing

list(d)

on a dictionary returns a list of all the keys
used in the dictionary, in insertion order (if you want it sorted, just use

sorted(d)

instead). To check whether a single key is in the
dictionary, use the

in

keyword.

Here is a small example using a dictionary:

>>> tel = {‘jack’: 4098, ‘sape’: 4139} >>> tel[‘guido’] = 4127 >>> tel {‘jack’: 4098, ‘sape’: 4139, ‘guido’: 4127} >>> tel[‘jack’] 4098 >>> del tel[‘sape’] >>> tel[‘irv’] = 4127 >>> tel {‘jack’: 4098, ‘guido’: 4127, ‘irv’: 4127} >>> list(tel) [‘jack’, ‘guido’, ‘irv’] >>> sorted(tel) [‘guido’, ‘irv’, ‘jack’] >>> ‘guido’ in tel True >>> ‘jack’ not in tel False

The

dict()

constructor builds dictionaries directly from sequences of
key-value pairs:

>>> dict([(‘sape’, 4139), (‘guido’, 4127), (‘jack’, 4098)]) {‘sape’: 4139, ‘guido’: 4127, ‘jack’: 4098}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

>>> dict(sape=4139, guido=4127, jack=4098) {‘sape’: 4139, ‘guido’: 4127, ‘jack’: 4098}

Unpacking Tuples Using Lambda Function

You can also use a

lambda

function to unpack tuples in Python. For example, you define a lambda function that takes two arguments and , and returns their sum. Use the operator to unpack the tuple and pass their contents as arguments to the

lambda

function. The result is the sum of the two values in the tuple, which is

15

.


# Unpacking tuples using lambda function tuples = (5, 10) result = (lambda x,y: x + y)(*tuples) print(result) # Output # 15

Python Full Course for free 🐍
Python Full Course for free 🐍

Unpacking Nested Tuples Using List Comprehension

You can also use list comprehension to unpack nested tuples in Python. For example, create a nested tuple with three tuples, each containing two values. You can use a list comprehension to iterate over each tuple in the

nested_tuple

, unpack the values using the syntax , and, and add them together to create a new list with the resulting values.


# Unpacking nested tuples # Using list comprehension nested_tuple = ((2, 4), (6, 8), (10, 12)) result = [x + y for x, y in nested_tuple] print(result) # Output # [6, 14, 22]

Follow the other example of a list comprehension to unpack nested tuples in Python.


# Unpacking nested tuples # Using list comprehension tuples = ((1, 3, 5), (7, 9, 11), (13, 15, 17)) result = [(x,y,z) for x,y,z in tuples] print(result) # Output # [(1, 3, 5), (7, 9, 11), (13, 15, 17)]

13.3.Swapping Values between Variables¶

This feature is used to enable swapping the values of two variables. With conventional assignment statements, we have to
use a temporary variable. For example, to swap and :

Tuple assignment solves this problem neatly:

The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. This feature makes tuple assignment quite versatile.

Python Tuple Unpacking
Python Tuple Unpacking

Reviewing Python tuples

Python defines a tuple using commas (), not parentheses

()

. For example, the following defines a tuple with two elements:


1,2

Code language: Python (python)

Python uses the parentheses to make the tuple clearer:


(1, 2)

Code language: Python (python)

Python also uses the parentheses to create an empty tuple:


()

Code language: Python (python)

In addition, you can use the

tuple()

constructor like this:


tuple()

Code language: Python (python)

To define a tuple with only one element, you still need to use a comma. The following example illustrates how to define a tuple with one element:


1,

Code language: Python (python)

It’s equivalent to the following:


(1, )

Code language: Python (python)

Note that the following is an integer, not a tuple:


(1)

Code language: Python (python)

5.Comparing Sequences and Other Types¶

Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:

(1, 2, 3) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] ‘ABC’ < ‘C’ < ‘Pascal’ < ‘Python’ (1, 2, 3, 4) < (1, 2, 4) (1, 2) < (1, 2, -1) (1, 2, 3) == (1.0, 2.0, 3.0) (1, 2, (‘aa’, ‘ab’)) < (1, 2, (‘abc’, ‘a’), 4)

Note that comparing objects of different types with or is legal
provided that the objects have appropriate comparison methods. For example,
mixed numeric types are compared according to their numeric value, so 0 equals
0.0, etc. Otherwise, rather than providing an arbitrary ordering, the
interpreter will raise a

TypeError

exception.

Footnotes

13.Tuple Assignment with Unpacking¶

Python has a very powerful tuple assignment feature that allows a tuple of variable names on the left of an assignment statement to be assigned values from a tuple on the right of the assignment. Another way to think of this is that the tuple of values is unpacked into the variable names.

This does the equivalent of seven assignment statements, all on one easy line.

Naturally, the number of variables on the left and the number of values on the right have to be the same.

Note

Unpacking into multiple variable names also works with lists, or any other sequence type, as long as there is exactly one value for each variable. For example, you can write

x, y = [3, 4]

.

why are TUPLES even a thing?
why are TUPLES even a thing?

13.3.Unpacking Into Iterator Variables¶

Multiple assignment with unpacking is particularly useful when you iterate through a list of tuples. You can unpack each tuple into several loop variables. For example:

On the first iteration the tuple

('Paul', 'Resnick')

is unpacked into the two variables

first_name

and

last_name

. One the second iteration, the next tuple is unpacked into those same loop variables.

Tuple Unpacking in Python

Tuple unpacking means pulling values apart from the tuple into separate variables.

Before jumping into details about tuple unpacking, let’s take a look at accessing tuple values in the first place.

How to Access Tuple Values in Python

In Python, you can access tuples with a similar syntax you would access an element from a list:

  1. Specify the index of the element you want to access.
  2. Use the square bracket accessing operator [] with the index to get the specific element.

Here is the syntax for accessing elements from a tuple:

tuple_values[index]

For example, let’s get the first coordinate of the tuple that represents a 3D point:

coords = 1, 2, 3 x = coords[0] print(x)

Output:

Tuple Unpacking

If you need to pick all the values from a tuple into variables, use tuple unpacking.

To do this, declare a comma-separated group of variable names and assign it to the tuple. To make this work, the number of variables must match the number of items in the tuple.

For example, let’s pick all the 3D coordinate values from a tuple into separate variables x, y, and z:

coords = 1, 2, 3 x, y, z = coords

This assigns the value 1 to x, 2 to y, and 3 to z.

The Number of Variables Must Equal to the Number of Elements

Make sure you always have the same number of elements on each side of the assignment operator when unpacking a tuple.

Let’s see what happens when the number of variables exceeds the number of elements in the tuple:

coords = 1, 2, 3 x, y, z, i, j, k = coords

Output:

ValueError: not enough values to unpack (expected 6, got 3)

As you can see, the unpacking failed because there are not enough values in the tuple to be assigned to 6 variables.

Also, if the number of new variables is less than the number of elements in the tuple, unpacking fails.

For example, let’s try to pick two values from a tuple of five:

coords = 1, 2, 3, 4, 5 x, y = coords

Output:

ValueError: too many values to unpack (expected 2)

Here the error says there are too many values to unpack. In the tuple, there are 5 values in total, whereas we only declare two variables to store them all.

Unpack Any Number of Elements with * Operator

In the previous section, you learned the left-hand side and the right-hand side of the tuple unpacking expression must have an equal number of items.

However, you can use a wildcard * to catch an arbitrary number of elements from a tuple. This is the only way you do not need to have an equal amount of items on both sides of the expression.

For example, let’s say you have a tuple of 3 coordinate values and 3 additional values that represent something else.

Let’s unpack the three first coordinate values into separate variables x, y, and z, and then store the rest of the values into a list:

coords = 1, 2, 3, 4, 5, 6 x, y, z, *rest = coords

Here 1 is assigned to x, 2 to y, 3 to z, and the rest of the values into rest.

You can verify this by printing the values:

print(f”x: {x}”) print(f”y: {y}”) print(f”z: {z}”) print(f”rest: {rest}”)

Output:

x: 1 y: 2 z: 3 rest: [4, 5, 6]

If you are wondering what the asterisk operator * does, please take a look at this article.

In short, it is a notation that represents any number of arguments. When you use this notation in a function in Python, you can pass that function to any number of arguments. When you use it with tuple unpacking, you are able to capture any number of “left-over” values.

Notice, that you do not necessarily need to capture the “rest” of the values. You can just as well capture the n middle values.

For example, let’s get the names occurring in the middle of a tuple:

coords = 0, 1, “two”, “three”, 4, 5 x, y, *strings, z, k = coords print(f”x: {x}”) print(f”y: {y}”) print(f”strings: {strings}”) print(f”z: {z}”) print(f”k: {k}”)

Output:

x: 0 y: 1 strings: [‘two’, ‘three’] z: 4 k: 5

Here the * operator unpacks any items between the first and the last two elements in the tuple. In this case, there are two strings. But there could be any number of those.

Python 3 Advanced Unpacking List and Tuple
Python 3 Advanced Unpacking List and Tuple

Unpacking Other Iterables in Python

In Python, tuple unpacking works for other iterable types as well. Even though we call it tuple unpacking, it should be more accurately called iterable unpacking.

For example, you can use unpacking syntax to pick values from a list or a dictionary.

Let’s see some basic examples of unpacking with other common iterable types in Python:

# List multiple assignments nums = [1, 2, 3] x, y, z = nums print(f”x:{x}, y:{y}, z:{z}”) # result: x:1, y:2, z:3 # String multiple assignments string = “Hey” l1, l2, l3 = string print(f”letter 1:'{l1}’, letter 2:'{l2}’, letter 3 :'{l3}'”) # result: letter 1:’H’, letter 2:’e’, letter 3 :’y’ # Dictionary multiple assignments data = {“name”: “Alice”, “age”: 30} (k1, v1), (k2, v2) = data.items() print(f”key1: {k1}, value1: {v1}”) print(f”key1: {k2}, value1: {v2}”) # result: # key1: name, value1: Alice # key1: age, value1: 30

Using the * operator on the right hand side

Python allows you to use the operator on the right-hand side. Suppose that you have two tuples:


odd_numbers = (1, 3, 5) even_numbers = (2, 4, 6)

Code language: Python (python)

The following example uses the operator to unpack those tuples and merge them into a single tuple:


numbers = (*odd_numbers, *even_numbers) print(numbers)

Code language: Python (python)

Output:


(1, 3, 5, 2, 4, 6)

Code language: Python (python)

Python 3 Class#21:--Tuple-Unpacking In  Python Functions
Python 3 Class#21:–Tuple-Unpacking In Python Functions

Unpacking a tuple

Unpacking a tuple means splitting the tuple’s elements into individual variables. For example:


x, y = (1, 2)

Code language: Python (python)

The left side:


x, y

Code language: Python (python)

is a tuple of two variables and .

The right side is also a tuple of two integers and .

The expression assigns the tuple elements on the right side (1, 2) to each variable on the left side (x, y) based on the relative position of each element.

In the above example, will take and will take .

See another example:


x, y ,z = 10, 20, 30

Code language: Python (python)

The right side is a tuple of three integers

10

,

20

, and

30

. You can quickly check its type as follows:


numbers = 10, 20, 30 print(type(numbers))

Code language: Python (python)

Output:

Code language: Python (python)

In the above example, the , , and variables will take the values

10

,

20

, and

30

respectively.

5.The del statement¶

There is a way to remove an item from a list given its index instead of its
value: the

del

statement. This differs from the

pop()

method
which returns a value. The

del

statement can also be used to remove
slices from a list or clear the entire list (which we did earlier by assignment
of an empty list to the slice). For example:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.25, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.25, 1234.5] >>> del a[:] >>> a []


del

can also be used to delete entire variables:

>>> del a

Referencing the name hereafter is an error (at least until another value
is assigned to it). We’ll find other uses for

del

later.

How to unpack a tuple in Python
How to unpack a tuple in Python

Using * Unpacking Method

You can use unpack operator * on a tuple to extract the individual elements from a tuple and assign its elements to a list by enclosing the tuple in square brackets

[]

and separating the elements with

commas

. For example, use the operator to unpack the elements of the

tuples

and assign them to the list

list1

. The resulting list contains the same elements as the original tuple, in the same order.


# Using * unpacking method tuples = ('Spark', 'Python', 'pandas', 'Java') # convert tuple into list list1 = [*tuples,] print(list1) # Output # ['Spark', 'Python', 'pandas', 'Java']

Conclusion

Today you learned about tuple unpacking in Python.

To recap, tuple unpacking means pulling apart all the values from a tuple into separate variables.

For example:

numbers = (1, 2 ,3) x, y, z = numbers

In Python, tuple unpacking works for other iterable types too. Due to this, a more general term for tuple unpacking is unpacking or multiple assignment.

Common use cases of tuple unpacking in Python include:

  • Assign values on one line of code.
  • For loops on dictionaries.
  • Avoid hard-coded indexes.
  • An alternative to slicing.
  • Deep unpacking.

Thanks for reading. I hope you find it useful.

Happy coding!

In Python, I can return multiple values from a function like this:


def myfunc(): return 1, 2, 3

When I call this function, I need to unpack the values like this:


a, b, c = myfunc() # a = 1, b = 2, c = 3

If I try this, I’ll get the whole tuple:


a = myfunc() # a = (1, 2, 3)

Is there anyway I can make the code above make

a = 1

without changing the way the function is called? I realize I can do something like

a, _, _ = myfunc()

, but I don’t want to change the way the function is called. I can only change the function definition.

In other words I want something like this:


a, b, c = myfunc() # a = 1, b = 2, c = 3 a, b = myfunc() # a = 1, b = 2 a = myfunc() # a = 1

Thanks for your help!

Sign in to your Python Morsels account to save your screencast settings.

Don’t have an account yet? Sign up here.

Let’s talk about how to unpack a tuple in Python. We’ll compare tuple unpacking to indexing tuples, both for code clarity and correctness.

tuple unpackingdefinition in Python Terminology.

We have a three-item tuple, called :


>>> p = (2, 1, 3)

We can access each of the things in this tuple by indexing it:


>>> print(p[0], p[1], p[2]) 2 1 3

But we could also give names to the things in this tuple:


>>> x, y, z = p

This is called tuple unpacking.
We’ve taken a three-item tuple and unpacked that tuple it into three variables (, , and ):


>>> print(x, y, z) 2 1 3

You can think of creating a tuple as packing values together and unpacking a tuple as undoing that work. We’re unpacking each of the values in our tuple above into separate variable names.

If we try to unpack a three-item tuple into just two variables, we’ll get an error:


>>> x, y = p Traceback (most recent call last): File "

", line 1, in

ValueError: too many values to unpack (expected 2)


Tuple unpacking describes the shape of the tuple you’re unpacking. So the number of variables you’re unpacking into must be the same as the number of items in the tuple-to-be-unpacked.

Tuple unpacking is really handy for avoiding hard-coded indexes and instead, giving descriptive names to each of the things inside a tuple.

Tuple unpacking is most often used, not with an equals sign, but instead in a

for

loop.

If we call the

items

method on a dictionary, we’ll get an iterable of two-item tuples:


>>> things = {"ducks": 2, "lamps": 3, "chairs": 0} >>> things.items() dict_items([('ducks', 2), ('lamps', 3), ('chairs', 0)])

These tuples represent the key-value pairs in our dictionary.


>>> for item in things.items(): ... print(item) ... ('ducks', 2) ('lamps', 3) ('chairs', 0)

We already know that we can unpack each of the things in each of these key-value tuples into two variables (say

thing

and

count

):


>>> for item in things.items(): ... thing, count = item ... print(thing, count) ... ducks 2 lamps 3 chairs 0

But we actually don’t even need an equals sign to do tuple unpacking.

Every iteration of a

for

loop does an implicit assignment.
The thing between the

for

and the

in

in a

for

loop, is very similar to the thing on the left-hand side of an equal sign in an assignment statement.

We can actually do that tuple unpacking right in the

for

line:


>>> for thing, count in things.items(): ... print(thing, count) ... ducks 2 lamps 3 chairs 0

We didn’t need that

item

variable at all.

We can do the tuple unpacking right inside the

for

loop itself because anything you can put on the left-hand side of the equal sign, you can put in between the

for

and the

in

in a

for

loop.
This is the most common place you’ll see tuple unpacking used: on the first line of a

for

loop.

Tuple unpacking is also called multiple assignment and it’s sometimes called iterable unpacking because you can actually use it with any iterable in Python, not just with tuples.

You’ll most often see tuple unpacking used when looping over an iterable of two-item tuples (or maybe an iterable of three-item tuples) but you can actually use tuple unpacking anywhere in your code where you’d like to give descriptive names to the things within a tuple.

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I’ll explain concepts that new Python programmers often overlook.

It’s tempting to reach for indexes when working with tuples, lists, and other sequences, but if we know the shape of the tuple we’re working with, we can unpack it instead.

Tuple unpacking (aka “multiple assignment” or “iterable unpacking”) is often underutilized by new Python programmers.

To track your progress on this Python Morsels topic trail, sign in or sign up.

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I’ll share ideas new Pythonistas often overlook.

Python 3 - Episode 18 - Packing and unpacking data
Python 3 – Episode 18 – Packing and unpacking data

Basics of unpacking a tuple and a list

By separating variables with commas () on the left side, you can assign elements of a tuple or list on the right side to each corresponding variable. The following examples use tuples, but the same approach applies to 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 the parentheses of a tuple 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 does not 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 prefix the variable name with an asterisk to assign the remaining elements as a list. This is described later.

Python3


test_list


[(


'Rash'


21


), (


'Varsha'


20


), (


'Kil'


19


)]


print


"The original list is : "


str


(test_list))


res


[tup[idx]


for


_, tup


in


enumerate


(test_list)


for


idx


in


range


len


(tup)


len


(tup))]


print


"List with only rear tuple element : "


str


(res))

Output

The original list is : [(1, ‘Rash’, 21), (2, ‘Varsha’, 20), (3, ‘Kil’, 19)]
List with only rear tuple element : [21, 20, 19]

Time complexity: O(nm), where n is the number of tuples in test_list and m is the length of the longest tuple. The enumerate() function and two nested loops iterate over all the elements in each tuple, so their time complexity is proportional to m. Therefore, the overall time complexity is O(nm).

Auxiliary space: O(n), where n is the number of tuples in test_list. The res list stores only the last element of each tuple, so its size is proportional to n. Therefore, the space complexity is O(n).

Method#5:Using numpy():

Algorithm:

  1. Import numpy module as np.
  2. Initialize a list of tuples called test_list.
  3. Print the original test_list.
  4. Convert the test_list to a numpy array using np.array().
  5. Extract the last column of the numpy array using numpy slicing with arr[:, -1].
  6. Store the extracted elements in a new list called res.
  7. Print the list with only the last element of each tuple.
Unpacking of List and Tuple - Python Tutorial12
Unpacking of List and Tuple – Python Tutorial12

Extended unpacking using the * operator

Sometimes, you don’t want to unpack every single item in a tuple. For example, you may want to unpack the first and second elements. In this case, you can use the operator. For example:


r, g, *other = (192, 210, 100, 0.5)

Code language: Python (python)

Output:


192 210 [100, 0.5]

Code language: Python (python)

In this example, Python assigns

192

to ,

210

to . Also, Python packs the remaining elements

100

and

0.5

into a list and assigns it to the

other

variable.

Notice that you can only use the operator once on the left-hand side of an unpacking assignment.

The following example results in error:


x, y, *z, *t = (10, 20, 30, '10:30')

Code language: Python (python)

Error:


SyntaxError: two starred expressions in assignment

Code language: Python (python)

Related Articles

  • Python Tuple Access with Example
  • Add Element to Tuple in Python
  • Add Elements of Tuples in Python
  • Append Element to a Tuple in Python
  • Python Empty Tuple with Examples
  • Python Tuple Slice with Examples
  • Python Tuple Length with Example
  • How to Sort List of Tuples in Python
  • Remove Last Element from Tuple in Python
  • Tuple as Dictionary Key in Python

While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print specific information from the tuple like rear index. For instance, a piece of code would want just names to be printed on all the student data. Let’s discuss certain ways in which one can achieve solutions to this problem.

Method #1: Using list comprehension

List comprehension is the simplest way in which this problem can be solved. We can just iterate over only the rear index value in all the index and store it in a list and print it after that.

3 - Python Tuples len and unpack
3 – Python Tuples len and unpack

Unpack with (asterisk)

When there are fewer variables than elements, prefixing the variable name with an asterisk 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 prefixed 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 prefix only one variable with . If multiple variables are prefixed with , 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 prefixed 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 # []

Python tuple unpacking means pulling values apart from a tuple.

For example:

x, y, z = (1, 2, 3)

This assigns 1 to x, 2 to y, and 3 to z.

In Python, unpacking is not limited to tuples only. You can unpack a list or a string with the same syntax.

Unpacking is more commonly known as multiple assignment, as it reminds of assigning multiple variables on the same line.

In this guide, you learn about Python tuples, tuple unpacking, and how to use tuple unpacking with other types.

When Use Tuple Unpacking in Python

So far you have learned you can use unpacking to tear apart values from an iterable in Python.

But when would you actually use such a feature?

Mainly, you can use tuple unpacking to shorten your code and to make it more readable. In the following sections, you are going to learn 5 common use cases for unpacking in Python.

Declare Multiple Values on the Same Line

The most obvious application of tuple unpacking is the ability to define multiple variables on the same line.

For example, instead of doing this:

a = 1 b = 2 c = 3

You can do:

a, b, c = 1, 2, 3

This expression makes the code shorter while it preserves the readability.

For Loops

In for loops, you commonly use unpacking syntax when looping through a dictionary. Perhaps this is something you have already done without realizing it is also tuple unpacking.

For example, let’s loop through a dictionary of data:

data = {“name”: “Alice”, “age”: 30} for key, value in data.items(): print(key, value)

Output:

name Alice age 30

The only difference doing this is you are not using the assignment operator =. Instead, you use the in operator

key, value in data.items()

. In this context, however, it does the exact same as the assignment operator. It assigns each key, value pair in the data dictionary to variables key and value one at a time.

Notice that this for loop could also be written this way:

data = {“name”: “Alice”, “age”: 30} for pair in data.items(): key, value = pair print(key, value)

Here the loop treats the key-value pairs as one object. Inside the loop, you then unpack the key and value info from it.

Avoid Hard-Coded Indexes

Sometimes your code may be littered with so-called hard-coded indexes, such as items[-1] or data[1].

Meanwhile, the meaning of these may be obvious to you, someone reading your code may need to spend time understanding your intentions.

Here is an example of how hard-coded indexes may look like:

print(f”The second element is data[1] and the last one is data[-1]”)

Usually, you can do a better job using unpacking instead of hard-coded indexes.

To demonstrate, let’s represent a date string (YYYY-MM-DD) in a different format (MM/DD/YYYY):

date = “2020-10-1” components = date.split(“-“) print(f”Today is {components[1]}/{components[2]}/{components[0]}”)

Output:

Today is 10/1/2020

This code is difficult to read due to the hard-coded indexes components[n].

To solve the problem, unpack year, month, and date to separate variables:

date = “2020-10-1” year, month, day = date.split(“-“) print(f”Today is {month}/{day}/{year}”)

Output:

Today is 10/1/2020

This drastically improves the readability of that piece of code, doesn’t it?

Slice Alternative

Similar to how you may write hard-coded indexes in your Python code, you may introduce hard-code slicing. This is usually bad practice as it also makes the code tougher to read.

For instance:

finish_order = [“Alice”, “Jack”, “Charlie”, “Bob”, “Emmanuel”, “John”] medalists = finish_order[:3] non_medalists = finish_order[3:] print(f”Gold: {medalists[0]}, Silver: {medalists[1]}, Bronze: {medalists[2]}”) print(f”Without medals: {‘, ‘.join(non_medalists)}”)

Output:

Gold: Alice, Silver: Jack, Bronze: Charlie Without medals: Bob, Emmanuel, John

Instead of specifying a hard-coded slice like finish_order[:3], you use unpacking:

finish_order = [“Alice”, “Jack”, “Charlie”, “Bob”, “Emmanuel”, “John”] first, second, third, *rest = finish_order print(f”Gold: {first}, Silver: {second}, Bronze: {third}”) print(f”Without medals: {‘, ‘.join(rest)}”)

Output:

Gold: Alice, Silver: Jack, Bronze: Charlie Without medals: Bob, Emmanuel, John

This way you did not even need to use slicing to get the job done.

For someone reading your code, it is clear what you want to accomplish with the following:

first, second, third, *rest = finish_order

While reading this takes a while to wrap your head around:

medalists = finish_order[:3] non_medalists = finish_order[3:]

Deep Unpacking

You can also use unpacking to unpack an unpacked object in one go. This is what is meant by “deep” unpacking.

For example, let’s create a tuple whose second argument is also a tuple. To access the inner tuple as one tuple, use the unpacking you learned today:

info = (“starting point”, (1, 2, 3)) name, point = info print(name, point)

Output:

starting point (1, 2, 3)

Here you unpacked two objects from the info tuple:

  • The name of the point.
  • The point as a 3D tuple.

But as the 3D point is also a tuple, you may want to unpack it too. To do this you can use deep unpacking to unpack an unpacked value in one go.

For example, let’s pull the x, y, and z values from the tuple inside the tuple:

info = (“starting point”, (1, 2, 3)) name, (x, y, z) = info print(name, x, y, z)

Output:

starting point 1 2 3

Keep in mind when doing this you need parenthesis. Otherwise, the program thinks you are trying to pick 4 values from a tuple with two objects.

Tuple unpacking in Python
Tuple unpacking in Python

Python3


test_list


[(


'Rash'


21


), (


'Varsha'


20


), (


'Kil'


19


)]


print


"The original list is : "


str


(test_list))


res


[]


for


tup


in


test_list:


res.append(tup[


])


print


"List with only rear tuple element : "


str


(res))

Output

The original list is : [(1, ‘Rash’, 21), (2, ‘Varsha’, 20), (3, ‘Kil’, 19)]
List with only rear tuple element : [21, 20, 19]

Time complexity: O(n), where n is the length of test_list because we iterate over each element in the list once.Auxiliary space: O(n), where n is the length of test_list because we create a new list called res with n elements.

Method 6: Using Loops

5.Tuples and Sequences¶

We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.

A tuple consists of a number of values separated by commas, for instance:

>>> t = 12345, 54321, ‘hello!’ >>> t[0] 12345 >>> t (12345, 54321, ‘hello!’) >>> # Tuples may be nested: … u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, ‘hello!’), (1, 2, 3, 4, 5)) >>> # Tuples are immutable: … t[0] = 88888 Traceback (most recent call last): File ”

“, line 1, in

TypeError: ‘tuple’ object does not support item assignment >>> # but they can contain mutable objects: … v = ([1, 2, 3], [3, 2, 1]) >>> v ([1, 2, 3], [3, 2, 1])

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different
situations and for different purposes.
Tuples are immutable, and usually contain a heterogeneous sequence of
elements that are accessed via unpacking (see later in this section) or indexing
(or even by attribute in the case of

namedtuples

).
Lists are mutable, and their elements are usually homogeneous and are
accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

>>> empty = () >>> singleton = ‘hello’, # <– note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton (‘hello’,)

The statement

t = 12345, 54321, 'hello!'

is an example of tuple packing:
the values

12345

,

54321

and

'hello!'

are packed together in a tuple.
The reverse operation is also possible:

>>> x, y, z = t

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

How to Unpack a tuple in several variables in Python
How to Unpack a tuple in several variables in Python

Using unpacking tuple to swap values of two variables

Traditionally, to swap the values of two variables, you would use a temporary variable like this:


x = 10 y = 20 print(f'x={x}, y={y}') tmp = x x = y y = tmp print(f'x={x}, y={y}')

Code language: Python (python)

Output:


x=10, y=20 x=20, y=10

Code language: Python (python)

In Python, you can use the unpacking tuple syntax to achieve the same result:


x = 10 y = 20 print(f'x={x}, y={y}') x, y = y, x print(f'x={x}, y={y}')

Code language: Python (python)

Output:


x=10, y=20 x=20, y=10

Code language: Python (python)

The following expression swaps the values of two variables, x and y.


x, y = y, x

Code language: Python (python)

In this expression, Python evaluates the right-hand side first and then assigns the variable from the left-hand side to the values from the right-hand side.

Unpacking Nested Tuples Using List Comprehension

You can also use list comprehension to unpack nested tuples in Python. For example, create a nested tuple with three tuples, each containing two values. You can use a list comprehension to iterate over each tuple in the

nested_tuple

, unpack the values using the syntax , and, and add them together to create a new list with the resulting values.


# Unpacking nested tuples # Using list comprehension nested_tuple = ((2, 4), (6, 8), (10, 12)) result = [x + y for x, y in nested_tuple] print(result) # Output # [6, 14, 22]

Follow the other example of a list comprehension to unpack nested tuples in Python.


# Unpacking nested tuples # Using list comprehension tuples = ((1, 3, 5), (7, 9, 11), (13, 15, 17)) result = [(x,y,z) for x,y,z in tuples] print(result) # Output # [(1, 3, 5), (7, 9, 11), (13, 15, 17)]

Unpack Tuples - Python Tutorial - w3Schools - Chapter-30 English
Unpack Tuples – Python Tutorial – w3Schools – Chapter-30 English

Keywords searched by users: tuple unpacking python 3

Tuple Unpacking In Python - Youtube
Tuple Unpacking In Python – Youtube
How To Unpack A Tuple In Several Variables In Python - Youtube
How To Unpack A Tuple In Several Variables In Python – Youtube
Unpacking A Tuple In Python - Youtube
Unpacking A Tuple In Python – Youtube
Python Tuples - Geeksforgeeks
Python Tuples – Geeksforgeeks
Learn Unpacking A Tuple In Python - Mind Luster
Learn Unpacking A Tuple In Python – Mind Luster
Tuples In Python With Real-Time Examples - Dot Net Tutorials
Tuples In Python With Real-Time Examples – Dot Net Tutorials

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *