Arabasta
Arabasta

Reputation: 815

Python: pair a single element with every element in a list

For example: myStr = 'z' is to be paired with myList = ['a','b','c'] so that the output is as follows:

['z','a']
['z','b']
['z','c']

A one-liner would be great!

I tried to do this:

print zip([myStr, x] for x in myList)

But the output was not quite as I wanted, as in here:

[(['z', 'a'],), (['z', 'b'],), (['z', 'c'],)]

Upvotes: 2

Views: 89

Answers (4)

Iron Fist
Iron Fist

Reputation: 10951

With zip:

>>> zip(myStr*3,myList)
[('z', 'a'), ('z', 'b'), ('z', 'c')]

Upvotes: 1

Paweł Kordowski
Paweł Kordowski

Reputation: 2768

from itertools import izip_longest
list(izip_longest([], ['a','b','c'], fillvalue='z'))

Upvotes: 0

Learner
Learner

Reputation: 5302

Itertools-izip-longest

>>>from itertools import izip_longest
>>>[list(i) for i  in list(izip_longest(['z'],['a','b','c'],fillvalue ='z'))]
>>>[['z', 'a'], ['z', 'b'], ['z', 'c']]

Upvotes: 0

pythad
pythad

Reputation: 4267

Try this:

myList = ['a','b','c']
myStr = 'z'
res = [[myStr, x] for x in myList]

Upvotes: 4

Related Questions