34

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?

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
fox
  • 15,428
  • 20
  • 55
  • 85

3 Answers3

58

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']
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 1
    also, `list('a' + suit for suit in suits)` – Burhan Khalid Apr 01 '13 at 06:19
  • @BurhanKhalid Unless for some reason you need a `tuple` eg. `tuple('a' + suit for suit in suits)`. I would definitely not use that for lists. – jamylak Apr 01 '13 at 06:20
  • @BurhanKhalid what's wrong with the list comprehension is the question – jamylak Apr 01 '13 at 07:46
  • @jamylak Works for beginning, but not end. so, e.g., `aces = [suit for suit in suits + "a"]` does not work. Any ideas on how to achieve that? – Don Apr 20 '16 at 18:52
  • 2
    @jamylak My dumbness. This works: `aces = [suit + "a" for suit in suits] ` – Don Apr 20 '16 at 19:02
8

Another alternative, the map function:

aces = map(( lambda x: 'a' + x), suits)
b2Wc0EKKOvLPn
  • 2,054
  • 13
  • 15
  • 3
    List comp is *usually* preferred when you need to have `lambda`s in your map, in which case they are also faster – jamylak Apr 01 '13 at 05:52
4

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']
bobrobbob
  • 1,251
  • 11
  • 21