1

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.

Klumbe
  • 370
  • 2
  • 12
  • Looks like you want the Walrus operator, `:=`. – Mark Ransom Feb 12 '22 at 14:13
  • @Mark: Sounds interesting, but seems not to work. Tried it with `for (n1,n2 := e) in a:` and even the other way around, but it throws a "cannot assign to named expression". Could you give a working example, please? – Klumbe Feb 14 '22 at 08:36
  • I wasn't actually 100% sure it would work, which is why I didn't leave an answer. Sorry to mislead you. – Mark Ransom Feb 14 '22 at 12:42

2 Answers2

2

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):
    ...
LeopardShark
  • 3,820
  • 2
  • 19
  • 33
  • 1
    Thanks, the zip-way works fine, but I would guess that it adds a lot complexity for having some syntactic sugar. The `as`-syntax is PHP, right? ;-) – Klumbe Feb 14 '22 at 08:40
  • @Klumbe `as` is also used for [a very similar feature when pattern matching](https://www.python.org/dev/peps/pep-0636/#capturing-matched-sub-patterns). – LeopardShark Feb 14 '22 at 08:51
0

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)
  • You missed the most important part of my question: `e` must be accessible. I am aware of the unpacking, but I am wondering if I can unpack it while still being able to use the full tuple. Thanks for your answer anyways, but it did not really answer the question. – Klumbe Feb 12 '22 at 12:01
  • Yeah, I did not notice that `e` also should be accessible. You can create a custom iterator where it will return tuple and unpacked data too. something likes this : [basic iterator](https://stackoverflow.com/questions/19151/how-to-build-a-basic-iterator). – Sumit Kumar Singh Feb 12 '22 at 13:58
  • Thanks again, but this is even way more work to do then just adding a single line doing `n1, n2 = e`. Searching for something built-in to Python ;-) Not sure whether it exists, since I tried to find something, but until now, I did not have any success. – Klumbe Feb 14 '22 at 08:42