3

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 !

Will
  • 24,082
  • 14
  • 97
  • 108
user3030473
  • 77
  • 1
  • 5

4 Answers4

2

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']
Community
  • 1
  • 1
ifma
  • 3,673
  • 4
  • 26
  • 38
  • While code often speaks for itself, it's good to add some explanation to your code. – Will Jul 09 '16 at 19:59
2

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

Will
  • 24,082
  • 14
  • 97
  • 108
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
1

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']
>>> 
joel goldstick
  • 4,393
  • 6
  • 30
  • 46
-2

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.

Yaelle
  • 401
  • 3
  • 5