Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a character to each item in a list [duplicate]

Tags:

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?

like image 253
fox Avatar asked Apr 01 '13 05:04

fox


People also ask

How do you add a character to each element in a list Python?

The Python list data type has three methods for adding elements: append() - appends a single element to the list. extend() - appends elements of an iterable to the list. insert() - inserts a single item at a given position of the list.

Can you have duplicate values in a list?

What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.

How do you add duplicates to a list in Python?

Method #1 : Using * operator We can employ * operator to multiply the occurrence of the particular value and hence can be used to perform this task of adding value multiple times in just a single line and makes it readable. # adds 3, 50 times.


2 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'] 
like image 161
jamylak Avatar answered Sep 30 '22 23:09

jamylak


Another alternative, the map function:

aces = map(( lambda x: 'a' + x), suits) 
like image 36
b2Wc0EKKOvLPn Avatar answered Oct 01 '22 00:10

b2Wc0EKKOvLPn