Reputation: 4330
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
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
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
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