Viach Kakovskyi
Viach Kakovskyi

Reputation: 1517

Python. Best way to "zip" char and list

I want to "zip" char and list in Python:

An example:

char = '<'
list = [3, 23, 67]

"zip"(char, list) 
 >>> [('<', 3), ('<', 23), ('<', 67)]

How I'm using itertools.repeat():

itertools.izip(itertools.repeat(char, len(list)), list)
>>>[('<', 3), ('<', 23), ('<', 67)]

It works, but it so interesting to find more pythonic solution.

Upvotes: 2

Views: 810

Answers (5)

njzk2
njzk2

Reputation: 39397

If you really want to use zip, here is how :

l  = [3, 23, 67]
zip('<' * len(l), l)

[('<', 3), ('<', 23), ('<', 67)]

In further details, itertools.repeat(char, len(list)) is quite similar in result to '<' * 3. Also, both work with zip (you could write zip(itertools.repeat(char, len(list)), l)), too).

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121824

If char is only ever going to be reused for all pairings, just use a list comprehension:

>>> [(char, i) for i in lst]
[('<', 3), ('<', 23), ('<', 67)]

If char is a string of characters, and you wanted to cycle through them when pairing (like zip() would for the shortest length sequence), use itertools.cycle():

>>> from itertools import cycle
>>> chars = 'fizz'
>>> lst = range(6)
>>> zip(chars, lst)
[('f', 0), ('i', 1), ('z', 2), ('z', 3)]
>>> zip(cycle(chars), lst)
[('f', 0), ('i', 1), ('z', 2), ('z', 3), ('f', 4), ('i', 5)]

Note how the characters of the string 'fizz' are reused to pair up with the numbers 4 and 5; they'll continue to be cycled to match any length list (which must be finite).

Upvotes: 1

Jeremy Brown
Jeremy Brown

Reputation: 18318

If you want something equivalent to your use of itertools - using lazy generation for iteration - then you can use generator expressions. The syntax is pretty much equivalent to list comprehensions except you enclose the expression with paranthesis.

>>> c = '<'
>>> l = [3, 23, 67]
>>> my_gen = ((c, item) for item in l)
>>> for item in my_gen:
...     print item
...
('<', 3)
('<', 23)
('<', 67)

For more info, here's the PEP that explains it: http://www.python.org/dev/peps/pep-0289/

Upvotes: 1

falsetru
falsetru

Reputation: 369064

You don't need itertools here.

Using list comprehension:

>>> char = '<'
>>> lst = [3, 23, 67]
>>> [(char, n) for n in lst]
[('<', 3), ('<', 23), ('<', 67)]

BTW, don't use list as a variable name. It shadows builtin function list.

Upvotes: 4

Daniel
Daniel

Reputation: 692

[(char, i) for i in list]

Naming your list as "list" is probably not a good idea btw., as this shadows the constructor for the internal list type.

Upvotes: 4

Related Questions