Home > Enterprise >  Is there a shorthand for tuple assignment in a for loop in Python?
Is there a shorthand for tuple assignment in a for loop in Python?

Time:02-13

Wondering if there is a shorter version of the following in Python 3:

a = [(1,2), (2,3), (1,4)]
for e in a:
    n1, n2 = e
    ...

Access to all three variables e, n1, n2 within the for-loop is required.

Thought of something like the following, but it isn't working.

for n1,n2=e in a:
    ...

The question has more of an academic character. I know it is not of a great importance.

CodePudding user response:

The most likely syntax would be

for (n1, n2) as e in a:
    ...

but, alas, no, this is not legal Python. You can still do

for (n1, n2), e in zip(a, a):
    ...

CodePudding user response:

for loop in python can unpack the iterated element.

so, the below code should give you the exact result:

a = [(1,2), (2,3), (1,4)]
for i,j in a:
    print(i,j)
# out:
# 1 2
# 2 3
# 1 4

basic iterator(specific to this case)

class Test(object):
    def __init__(self, values):
        self.values = values

    def __iter__(self):
        for tple in self.values:
            yield (*tple,tple)

case1 = Test([(1,2), (2,3), (1,4)])
for i,j,e in case1:
    print(i,j,e)
# out:
1 2 (1, 2)
2 3 (2, 3)
1 4 (1, 4)
  • Related