Daniel Daniel - 11 months ago 39
Python Question

Adding same string string repeatedly to a list to make it a tuple

I'm trying to combine a string with a series of numbers as tuples to a list.

For example, starting with:

a = [12,23,45,67,89]
string = "John"

I want to turn that into:

tuples = [(12,'John'),(23,'John'),(45,'John'),(67,'John'),(89,'John')]

I tried:

string2 = string * len(a)
tuples = zip(a, string2)

but this returned:

tuples = [(12,'J'), (23,'o'), ...]

Answer Source
>>> a = [12,23,45,67,89]
>>> string = "John"
>>> my_tuple = [(i,string) for i in a]
>>> print my_tuple

You can iterate over each position within a string so zip causes the behavior you were seeing previously.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download