Add a character to each item in a list

Question:

Suppose I have a list of suits of cards as follows:

suits = ["h","c", "d", "s"]

and I want to add a type of card to each suit, so that my result is something like

aces = ["ah","ac", "ad", "as"]

is there an easy way to do this without recreating an entirely new list and using a for loop?

Asked By: fox

||

Answers:

This would have to be the ‘easiest’ way

>>> suits = ["h","c", "d", "s"]
>>> aces = ["a" + suit for suit in suits]
>>> aces
['ah', 'ac', 'ad', 'as']
Answered By: jamylak

Another alternative, the map function:

aces = map(( lambda x: 'a' + x), suits)
Answered By: b2Wc0EKKOvLPn

If you want to add something different than always ‘a’ you can try this too:

foo = ['h','c', 'd', 's']
bar = ['a','b','c','d']
baz = [x+y for x, y in zip(foo, bar)]
>>> ['ha', 'cb', 'dc', 'sd']
Answered By: bobrobbob
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.