I have a tuple like this
rows = ((1L, 100000L, 'logo', '0'), (2L, 100000L, 'menu', '0'))
And I want to turn it into this
[[1L, 100000L, 'logo', '0'], [2L, 100000L, 'menu', '0']]
Here is what I am trying
for idx, val in enumerate(rows):
print list(rows[idx])
And
for idx, val in enumerate(rows):
print list(val)
but neither prints out anything and there is no error. It just doesn't do anything. I know the variable rows has this value because I print it out before I go thought the loop.
How can I turn the tuple in to an array of arrays?
3 Answers 3
Try this:
list(map(list, rows))
The built-in list converts anything into a list that is iterable, i.e. you can write a forloop for it. The map applies the function list to the tuples inside the tuple.
An alternative would be a nested list comprehension:
[[x for x in t] for t in rows]
List comprehensions are essentially loops in one line. They can only contain expressions. "Normal" loops can contain statements and are typically better suited for multi-line solutions.
Comments
What about:
new_rows = []
for i in rows:
rows.append(list(i))
Comments
This seems to work for me:
>>> rows = ((1L, 100000L, 'logo', '0'), (2L, 100000L, 'menu', '0'))
>>> [list(x) for x in rows]
[[1L, 100000L, 'logo', '0'], [2L, 100000L, 'menu', '0']]