raph c
raph c

Reputation: 73

Unpack tuples from list of tuples

I would like to unpack the variables from a list of list of tuples. I have made some attempts but could not reach a solution.

Here is a list of points. I would like to unpack each variable inside p1, p2, p3, p4 during each iteration of the sublists so that during each iteration each variable gets assigned.

For example in the first iteration, I would expect:

p1=(0,0)
p2=(1,0)
p3=(2,0)
p4=(0,1)

In the next iteration:

p1=(0,0)
p2=(1,0)
p3=(2,0)
p4=(2,1)
points=[[(0, 0), (1, 0), (2, 0), (0, 1)],[(0, 0), (1, 0), (2, 0), (2, 1)]]
        
for i in points:
    for j in i:
         p1=j[0],j[1]
         p2=j[0],j[1]
         p3=j[0],j[1]
         p4=j[0],j[1]

Upvotes: 0

Views: 79

Answers (3)

Puchi
Puchi

Reputation: 1

You need to use enumerate:

points=[[(0, 0), (1, 0), (2, 0), (0, 1)],[(0, 0), (1, 0), (2, 0), (2, 1)]]
for i in points:
 
    for index, j in enumerate(i):
        print(f"P{index +1 }:{j}")

Result:

P1:(0, 0)
P2:(1, 0)
P3:(2, 0)
P4:(0, 1)
P1:(0, 0)
P2:(1, 0)
P3:(2, 0)
P4:(2, 1)

Upvotes: 0

BrokenBenchmark
BrokenBenchmark

Reputation: 19251

Each element of points is a list of tuples that can be unpacked, like so:

for p1, p2, p3, p4 in points:
    print(p1, p2, p3, p4)

This outputs:

(0, 0) (1, 0) (2, 0) (0, 1)
(0, 0) (1, 0) (2, 0) (2, 1)

Upvotes: 1

nicomp
nicomp

Reputation: 4647

I corrected sub to points and I fixed the index that was out of bounds when unpacking p2.

points=[[(0, 0), (1, 0), (2, 0), (0, 1)],[(0, 0), (1, 0), (2, 0), (2, 1)]]
        
for i in points:
    for j in i:
         p1=j[0],j[1]
         p2=j[0],j[1]
         p3=j[0],j[1]
         p4=j[0],j[1]
        
        
    print (p1,p2,p3,p4)

Upvotes: 0

Related Questions