hssss
hssss

Reputation: 141

appending a string to another string

I have 2 lists :

list1 contains "T" "F" "T" "T"

list2 contains "a" "b" "c" "d"

I want to create a third list such that I append element1 in list1 to element1 in list2.

So list3 would be the following: "Ta" "Fb" "Tc" "Td"

How can i do that?

Upvotes: 0

Views: 147

Answers (3)

johnsyweb
johnsyweb

Reputation: 141780

zip, as others have suggested, is good. izip, I would suggest, is better for longer lists.

>>> from itertools import izip
>>> list3 = [x+y for x,y in izip(list1, list2)]
>>> list3
['Ta', 'Fb', 'Tc', 'Td']

See also the documentation on list comprehensions, they're an essential tool in Python programming.

Upvotes: 1

pyfunc
pyfunc

Reputation: 66709

Your lists

>>> t = ["T", "F", "T", "T"]
>>> t1 = ["a", "b", "c", "d"]

Group them using zip function:

>>> t2 = zip(t, t1)
>>> t2
[('T', 'a'), ('F', 'b'), ('T', 'c'), ('T', 'd')]

You could now manipulate the list for desired result:

>>> ["".join(x) for x in t2]
['Ta', 'Fb', 'Tc', 'Td']
>>> 

Upvotes: 0

Karl Knechtel
Karl Knechtel

Reputation: 61498

Use zip: [x + y for x, y in zip(list1, list2)].

Upvotes: 4

Related Questions