Reputation: 356
I have this array:
lst = ['A', 'B', 'C']
How could I append a string 'D' to each element and convert every set as a tuple:
lst2= [('A', 'D'),
('B', 'D'),
('C', 'D')]
Upvotes: 0
Views: 4347
Reputation: 17834
You can use the function product()
:
from itertools import product
lst = ['A', 'B', 'C']
list(product(lst, 'D'))
# [('A', 'D'), ('B', 'D'), ('C', 'D')]
Upvotes: 1
Reputation: 142
list1 = ['A', 'B', 'C']
list2 = []
for i in list1:
list2.append((i, 'D'))
print(list2)
Upvotes: 1
Reputation:
alternative solution is use zip_longest
from itertools import zip_longest
list(zip_longest(['A', 'B', 'C'], [], fillvalue='D'))
the result wiil be:
[('A', 'D'), ('B', 'D'), ('C', 'D')]
Upvotes: 3
Reputation: 10792
Another option using zip:
x = ['A', 'B', 'C']
res = list(zip(x,'D'*len(x)))
Upvotes: 1
Reputation: 236034
Like this, using a list comprehension:
lst = ['A', 'B', 'C']
lst2 = [(x, 'D') for x in lst]
lst2
=> [('A', 'D'), ('B', 'D'), ('C', 'D')]
By the way, it's a bad idea to call a variable list
, that clashes with a built-in function. I renamed it.
Upvotes: 5
Reputation: 91059
list2 = [(i, 'D') for i in list]
(apart from the fact that list
is a very bad variable name)
Upvotes: 1