By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,994 Members | 1,285 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,994 IT Pros & Developers. It's quick & easy.

How to convert a list of tuples to a list of lists?

P: 2
[(1, red), (2, blue), (3, green)]

how do I convert to:

[[1, red], [2, blue], [3, green]]

thanks
Feb 26 '11 #1
Share this Question
Share on Google+
4 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Expand|Select|Wrap|Line Numbers
  1. >>> seq1 = [(1, 'red'), (2, 'blue'), (3, 'green')]
  2. >>>[list(item) for item in seq1]
  3. [[1, 'red'], [2, 'blue'], [3, 'green']]
  4. >>> 
Feb 26 '11 #2

P: 2
It's still returning a list of tuples:
Expand|Select|Wrap|Line Numbers
  1. seq1 = [(1, 'red'), (2, 'blue'), (3, 'green')][list(item) for item in seq1]
  2. print seq1
>>>
[(1, 'red'), (2, 'blue'), (3, 'green')]
>>>
Feb 27 '11 #3

bvdet
Expert Mod 2.5K+
P: 2,851
You are not making an assignment of the new structure to seq1.
Feb 27 '11 #4

Expert 100+
P: 624
You can also use a for() loop if you don't understand list comprehensions. Iterate through the list, cast each tuple to a list, and append this list to a new, outer list.
Feb 27 '11 #5

Post your reply

Sign in to post your reply or Sign up for a free account.