T.M
T.M

Reputation: 93

adding the same variable to a list of tuples

I've the below 3 lists and a value (country[i]) and i want to add the same country[i] to all tuples available:

name = ["a", "b", "c"]
age = [1, 2, 3]
city = ["aaa", "bbb", "ccc"]
country[i]

where country[i] equals to "United States", And i used the following code:

user_info = [tuple((t,)) for t in zip(name, age, city, country[i])]

When executed i got the following result:

[(('a', 1, 'aaa', 'U'),), (('b', 2, 'bbb', 'n'),), (('c', 3, 'ccc', 'i'),)]

While what i want is:

[('a', 1, 'aaa', 'United States'), ('b', 2, 'bbb', 'United States'), ('c', 3, 'ccc', 'United States)]

Upvotes: 1

Views: 50

Answers (3)

micgeronimo
micgeronimo

Reputation: 2149

result = [my_tuple + ('United States',) for my_tuple in zip(name, age, city)]

Maybe you have list of countries, then

result = [my_tuple + (country,) for my_tuple in zip(name, age, city) for country in countries]

Upvotes: 1

Rolf Lussi
Rolf Lussi

Reputation: 615

since country[i] is just "United States" you step through the string with the for loop. So you get each single letter. The list of countries need to be same long as the one of cities.

So it should be

country[i] = ["United States", "United States", "United States"]

or easier

country[i] = ["United States"]*3

or you dont step through the country if you have just one

Upvotes: 0

alecxe
alecxe

Reputation: 473873

You can add it to each of the item "manually":

v = (country[i], )
[t + v for t in zip(name, age, city)]

Demo:

>>> country = ["United States"]
>>> i = 0
>>> name = ["a", "b", "c"]
>>> age = [1, 2, 3]
>>> city = ["aaa", "bbb", "ccc"]
>>> v = (country[i], )
>>> [t + v for t in zip(name, age, city)]
[('a', 1, 'aaa', 'United States'), ('b', 2, 'bbb', 'United States'), ('c', 3, 'ccc', 'United States')]

Upvotes: 2

Related Questions