Pankaj
Pankaj

Reputation: 2678

Adding multiple tuples to a list

I want to add all co-ordinates of line as shown below

coordinates = []    
for line in lines:
        for x1,y1,x2,y2 in line:
            coordinates.extend((x1,y1),(x2,y2))

To retrieve x and y co-ordinates later for further calculation

x,y = zip(*coordinates)

I get error TypeError: extend() takes exactly one argument (2 given). How can I achieve above without calling extend twice

coordinates.extend((x1,y1))  
coordinates.extend((x2,y2))   

Upvotes: 1

Views: 4507

Answers (4)

neV_
neV_

Reputation: 53

The elements should be in a tuple or list

coordinates.extend(((x1, y1), (x2, y2)))

Also the behaviour achieved by

coordinates.extend((x1, y1))
coordinates.extend((x2, y2))

can be achieved with

coordinates.extend((x1, y1, x2, y2))

Upvotes: 2

user2390182
user2390182

Reputation: 73460

You can wrap the entire process into one comprehension:

coordinates =  [pair for line in lines for pair in (line[:2], line[2:])]

Or if the lines aren't tuples themselves:

coordinates =  [p for l in lines for p in map(tuple, (l[:2], l[2:]))]

Upvotes: 0

Shreeyansh Jain
Shreeyansh Jain

Reputation: 1495

Use list inside extend as extend iterate over list and append all elements in it.

coordinates.extend([(x1, y1), (x2, y2)])

co =[]

co.extend([(1,2), (3,4)])

co

[(1, 2), (3, 4)]

Upvotes: 2

ubadub
ubadub

Reputation: 3880

coardinates.extend([(x1,y1),(x2,y2)])

Or you can put the whole thing in a list comprehension:

from itertools import chain
coardinates = list(chain.from_iterable(((x1,y1), (x2,y2))) for line in lines for x1,y1,x2,y2 in line)

Upvotes: 2

Related Questions