Rainie Hu
Rainie Hu

Reputation: 71

Python: How to convert a list to a list of tuples?

for example, i have a list below,

['Visa', 'Rogers', 'Visa']

if i want to convert it to a list of tuples, like

[('Visa',), ('Rogers',), ('Visa',)]

How can I convert it?

Upvotes: 0

Views: 44

Answers (2)

R Nar
R Nar

Reputation: 5515

>>> [(x,) for x in ['Visa', 'Rogers', 'Visa']]
[('Visa',), ('Rogers',), ('Visa',)]

simple list comprehension will do the trick. make sure to have the , to specify single item tuples (you will just have the original strings instead)

Upvotes: 3

Felk
Felk

Reputation: 8224

Doing some kind of operation for each element can be done with map() or list comprehensions:

a = ['Visa', 'Rogers', 'Visa']

b = [(v,) for v in a]
c = map(lambda v: (v,), a)

print(b) # [('Visa',), ('Rogers',), ('Visa',)]
print(c) # [('Visa',), ('Rogers',), ('Visa',)]

Please keep in mind that 1-element-tuples are represented as (value,) to distinguish them from just a grouping/regular parantheses

Upvotes: 2

Related Questions