Snehal Parmar
Snehal Parmar

Reputation: 5851

Converting each element of a list to tuple

to convert each element of list to tuple like following :

l = ['abc','xyz','test']

convert to tuple list:

newl = [('abc',),('xyz',),('test',)]

Actually I have dict with keys like this so for searching purpose I need to have these.

Upvotes: 7

Views: 14611

Answers (2)

user2555451
user2555451

Reputation:

You can use a list comprehension:

>>> l = ['abc','xyz','test']
>>> [(x,) for x in l]
[('abc',), ('xyz',), ('test',)]
>>>

Or, if you are on Python 2.x, you could just use zip:

>>> # Python 2.x interpreter
>>> l = ['abc','xyz','test']
>>> zip(l)
[('abc',), ('xyz',), ('test',)]
>>>

However, the previous solution will not work in Python 3.x because zip now returns a zip object. Instead, you would need to explicitly make the results a list by placing them in list:

>>> # Python 3.x interpreter
>>> l = ['abc','xyz','test']
>>> zip(l)
<zip object at 0x020A3170>
>>> list(zip(l))
[('abc',), ('xyz',), ('test',)]
>>>

I personally prefer the list comprehension over this last solution though.

Upvotes: 17

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

Just do this:

newl = [(i, ) for i in l]

Upvotes: 2

Related Questions