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?
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']
Another alternative, the map function:
aces = map(( lambda x: 'a' + x), suits)
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']
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?
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']
Another alternative, the map function:
aces = map(( lambda x: 'a' + x), suits)
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']