Gianni Spear
Gianni Spear

Reputation: 7924

Python zip the first element of a list with the rest of elements

I have a list

mylist = [(0,0,0),(1,1,1),(2,2,2),(3,3,3)]

i wish to find a code saving method to zip the first element mylist[0] with the rest of the list element mylist[1:] in order to get a new list as:

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

Upvotes: 2

Views: 2293

Answers (3)

mdml
mdml

Reputation: 22882

Using zip:

>>> mylist = [(0,0,0),(1,1,1),(2,2,2),(3,3,3)]
>>> zip([mylist[0]]*(len(mylist)-1), mylist[1:])
[((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 2, 2)), ((0, 0, 0), (3, 3, 3))]

A list comprehension is even simpler:

>>> [ (mylist[0], sublist) for sublist in mylist[1:] ]
[((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 2, 2)), ((0, 0, 0), (3, 3, 3))]

Upvotes: 9

venpa
venpa

Reputation: 4318

Using map:

map(lambda x:(mylist[0],x),mylist[1:])

Output:

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

Upvotes: 4

user2555451
user2555451

Reputation:

I don't think that zip is necessary here. A list comprehension will work fine:

>>> mylist = [(0,0,0),(1,1,1),(2,2,2),(3,3,3)]
>>> [(mylist[0], x) for x in mylist[1:]]
[((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 2, 2)), ((0, 0, 0), (3, 3, 3))]
>>>

Upvotes: 8

Related Questions