Questions tagged [iterable-unpacking]

A Python feature in which elements of an iterable are simultaneously assigned to multiple variables, e.g. a, b, c = [1, 2, 3].

Iterable unpacking (sometimes known as 'tuple unpacking', although the concept applies equally to any iterable, not just tuples) is a feature of Python which allows for the assignment of the elements of an iterable to be assigned to multiple variables:

>>> a, b, c = [1, 2, 3]
>>> a
1
>>> b
2
>>> c
3

This feature can be used to swap the values of two variables without the use of a temporary 'holding' variable, as traditionally employed in other languages:

>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1
>>> # rather than:
... a = 1
>>> b = 2
>>> temp = a
>>> a = b
>>> b = temp
>>> a
2
>>> b
1

If the number of elements in the iterable does not match the number of variables on the left hand side of the assignment, A ValueError is raised:

>>> d, e = 4, 5, 6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> f, g, h = 7, 8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

Since Python 3, Extended iterable unpacking allows "spare" elements of the iterable to be assigned to a list (note the *):

>>> x, *y, z = "kapow"
>>> x
'k'
>>> y
['a', 'p', 'o']
>>> z
'w'
469 questions
0
votes
0 answers

My Python code runs successfully, but when imported as a module it gives 'cannot unpack non-iterable NoneType object'

import os import sys import shutil from src.logger import logging from src.exception import CustomException from dataclasses import dataclass ## intitialize the Data Ingestion configuration @dataclass class DataIngestionconfig: …
0
votes
1 answer

Why is my second variable (x2,y2) not defined while my first variable (x1,y1) is?

class Line(): def __init__(self, coor1 , coor2): self.coor1 = coor1 self.coor2 = coor2 def distance(self): for x1,y1 in self.coor1, x2,y2 in self.coor2: …
0
votes
2 answers

Arbitrary Amount of Tuple Unpacking With Common Date

Input datas2 = [[("01/01/2011", 1), ("02/02/2011", "No"), ("03/03/2011", 11)], [("01/01/2011", 2), ("03/03/2011", 22), ("22/22/2222", "no")], [("01/01/2011", 3), ("03/03/2011", 33), ("22/22/2222", "333")]] Intended Output [("01/01/2011", 1, 2, 3),…
hhh
  • 50,788
  • 62
  • 179
  • 282
0
votes
2 answers

How to unpack a list of ints and print them so they have a preceding zero?

I have a list of [##, ##, ## ... ##] and I want to unpack it and print it as "##-##-##-...-##" with preceding zeros on the left if the number is less than ten. Is there a way to do this besides a for loop? I don't want the trailing "-" at the end.
MiguelP
  • 416
  • 2
  • 12
0
votes
4 answers

Adding items from one list to another list of lists

Suppose I have the following lists: list_1 = [[1,2],[3,4],[5,6],[7,8]] list_2 = [11,12,13,14] How can I add items from the second list to each of the items from the first one? Stated clearly, this is the result I'm looking for: desired_output =…
Felipe D.
  • 1,157
  • 9
  • 19
0
votes
1 answer

Unpacking a list of tuples of func, *args, **kwargs / command design pattern

I have a routine that will take a list of tuples in the form: (function, [optional] arguments, [optional] keyword arguments) as part of a Command design pattern implementation. ORG1_PROCESS = [(add_header_row, df, COLUMN_LABELS['ORG1']), …
user1330734
  • 390
  • 6
  • 21
0
votes
1 answer

DolphinDB equivalent for Unpacking in Python

For the following "t" table, “name_set” is the name of its 3 columns. How can I write a SQL script to perform python-like unpacking as I want to select all the columns in “name_set”?
Zoey
  • 48
  • 5
0
votes
1 answer

Condensing tuple of tuple of tuples of tuples of... into a list of reduced items

I have an iterable with a lot of nesting - not always to equal depth, but guarantees that each element of the original is at least once-iterable - I define this in the block quote below. An item is more than once iterable if all its elements are…
Orion Yeung
  • 141
  • 1
  • 5
0
votes
1 answer

Python: Unpacking elements of nested lists in a for-loop

I have the following code: queries = [[0, 3], [2, 5], [2, 4]] for x, y in queries: ... I understand that this is utilizing "tuple unpacking" I don't quite understand how the "x" and "y" in the for-loop point to the first and second elements…
0
votes
2 answers

Find an index in a list of lists using an index inside one of the lists in pyton

I'm trying to determine if there is a way to access an index essentially by making a list of lists, where each inner list has a tuple that provides essentially grid coordinates, i.e: example = [ ['a', (0,0)], ['b',(0,1)], ['c', (0,2)], …
Patrick
  • 3
  • 1
0
votes
2 answers

Getting integers from a tuple saved then loaded with pickle

On Python, I made a module for saving and loading integers, It can save roughly as I want it (I am using Pickle) but when I load it I receive my integers in tuple-form (because I made it a tuple to save) I want to assign the components of the tuple…
0
votes
0 answers

Unpacking of a dictionary in Python with **kwargs

I have a code snippet which is as follows: def myfunc(**kwargs): print("I work with the follwoing people: ") for people in kwargs: print (kwargs[people]) mydict = {'person1': "Faraz", 'person2': "Rukhshan", 'person3':…
Reactoo
  • 916
  • 2
  • 12
  • 40
0
votes
1 answer

How to automatically unpack list that contains some 0 values?

When I try to unpack a list data for a MySQL database query that has some columns with value 0, I get an error. Name (varchar) Apples(int) Candies(int) Color (varchar) John 5 0 Blue If I unpack my query result like: name, apples,…
pandasw
  • 3
  • 2
0
votes
0 answers

Type hint for arbitary tuple unpacking

Having # python3.9 TypeA = tuple[int, float, int, str] TypeB = tuple[int, str, set] T = TypeVar("T", TypeA, TypeB) def f(x: int) -> int: return x * x def yielding_function(payload: Iterable[T]) -> Iterator[T]: for x0, *other in payload: …
vahvero
  • 525
  • 11
  • 24
0
votes
2 answers

Expand tuple to parameters pack in member initializer lists

I need to initialize a base class with arguments stored in a std::tuple. I have access to C++17 and managed to figure out that std::make_from_tuple may work but would require a copy constructor for the base class. An example: #include…
CaTo
  • 69
  • 1
  • 8