Anurag Ramdasan
Anurag Ramdasan

Reputation: 4330

list of strings to list of tuples of string

I have a list of strings of the sort

['aaa','bbb','ccc']

I need to convert them into a list of tuples like this,

[('aaa',),('bbb',),('ccc',)]

When I try to apply the tuple function to each element of the list, it splits the string and returns something of the sort

('a','a','a')

Is there a way to work around this issue?

Upvotes: 2

Views: 142

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213223

Don't apply tuple function, since it takes the string as sequence, and breaks it's characters apart. You can simply build tuple manually with List Comprehensionlike this:

>>> l = ['aaa','bbb','ccc']
>>> [(elem,) for elem in l]
[('aaa',), ('bbb',), ('ccc',)]

Upvotes: 2

Inbar Rose
Inbar Rose

Reputation: 43437

Using list comprehension, and tuple creation via the 'single item tuple creation method' or look here for information about this.

lst = ['aaa','bbb','ccc']
tpl_lst = [(i,) for i in lst]

Yields:

[('aaa',), ('bbb',), ('ccc',)]

Upvotes: 3

Volatility
Volatility

Reputation: 32300

>>> l = ['aaa', 'bbb', 'ccc']
>>> print [(i,) for i in l]
[('aaa',), ('bbb',), ('ccc',)]

All you need to do is put each element in its own one-tuple.

Upvotes: 2

Related Questions