user3030473
user3030473

Reputation: 77

Python append to an string element in a list

I'm fairly new to python. I want to know how can you append to a string element in a list cumulatively ?

list = ['1','2','3','4']
list2 = ['a','b','c','d']

I want a new list like this:

list3 = ['1a', '1b', '1c', '1d']

I've been running circles for possible answers. Help is much appreciated, thanks !

Upvotes: 3

Views: 477

Answers (4)

Yaelle
Yaelle

Reputation: 391

I'm assuming your goal is [ '1a', '2b', '3c', '4d' ] ?

list = [ '1', '2', '3', '4' ]
list2 = [ 'a', 'b', 'c', 'd' ]
list3 = []

for i in range (len(list)):
    elem = list[i] + list2[i]
    list3 += [ elem ]

print list3

In general though, I'd be careful about doing this. There's no check here that the lists are the same length, so if list is longer than list2, you'd get an error, and if list is shorter than list2, you'd miss information.

I would do this specific problem like this:

letters = [ 'a', 'b', 'c', 'd' ]
numberedLetters = []

for i in range (len(letters)):
    numberedLetters += [ str(i+1) + letters[ i ] ]

print numberedLetters

And agree with the other posters, don't name your variable 'list' - not only because it's a keyword, but because variable names should be as informative as reasonably possible.

Upvotes: -2

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34257

You can use map() and zip like so:

list = ['1','2','3','4']
list2 = ['a','b','c','d'] 

print map(lambda x: x[0] + x[1],zip(list,list2))

Output:

['1a', '2b', '3c', '4d']

Online Demo - https://repl.it/CaTY

Upvotes: 2

joel goldstick
joel goldstick

Reputation: 4493

In your question you want list3 = ['1a', '1b', '1c', '1d'].

If you really want this: list3 = ['1a', '2b', '3c', '4d'] then:

>>> list = ['1','2','3','4']
>>> list2 = ['a','b','c','d'] 
>>> zip(list, list2)
[('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd')]
>>> l3 = zip(list, list2)
>>> l4 = [x[0]+x[1] for x in l3]
>>> l4
['1a', '2b', '3c', '4d']
>>> 

Upvotes: 1

ifma
ifma

Reputation: 3818

Using list comprehension. Note that you need to turn the integer into a string via the str() function, then you can use string concatenation to combine list1[0] and every element in list2. Also note that list is a keyword in python, so it is not a good name for a variable.

>>> list1 = [1,2,3,4]
>>> list2 = ['a','b','c','d']
>>> list3 = [str(list1[0]) + char for char in list2]
>>> list3
['1a', '1b', '1c', '1d']

Upvotes: 2

Related Questions