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?
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With