1

I'm stuck on this very basic issue. How do I convert a tuple inside a list into a list.

For example,

[(23,5,6,4)]=>[23,5,6,4]

This is a very basic issue, & I have done this using for loops. But is there a better wayt to do it?

  def make_list(item):
  ''' Helper for get_alert
  '''
  temp = []
  for inst in item:
     temp.append(inst)
  return temp
souvickcse
  • 7,742
  • 5
  • 37
  • 64
Django
  • 181
  • 2
  • 15
  • none of the possible duplicates mention the nested use of a tuple – olly_uk Jun 25 '14 at 17:12
  • @olly_uk your comment does not make any sense, because (almost) all solutions from the linked duplicate will work on tuples. – vaultah Jun 25 '14 at 17:19
  • yes they will work on tuples, but do not specifically state tuples, i.e. a lesser python user may not know that those methods can be applied to both lists & tuples – olly_uk Jun 26 '14 at 08:23

3 Answers3

6
x = [(23,5,6,4)]
x = list(x[0])
print(x)

Result:

[23, 5, 6, 4]
Kevin
  • 74,910
  • 12
  • 133
  • 166
3

You can try the following:

new = [item for sub in lst for item in sub]

This runs as:

>>> lst = [(2, 3, 4, 5)]
>>> new = [item for sub in lst for item in sub]
>>> new
[2, 3, 4, 5]
>>> 

This uses nested for loops as a list comprehension. Here is the extended form of the above:

lst = [(2, 3, 4, 5)]
new = []
for sub in lst:
    for item in sub:
        new.append(item)

Which runs as:

>>> lst = [(2, 3, 4, 5)]
>>> new = []
>>> for sub in lst:
...     for item in sub:
...         new.append(item)
... 
>>> new
[2, 3, 4, 5]
>>> 

As you can see, both of these work the same, only with the list comprehension being more pythonic and efficient.

  • 1
    Just a side note -- for the particular case that OP has, the method given by Kevin is cleaner (It takes up less space and is easier to read). However, this method is much more general, working on any list of iterables, while the other method only works on a singleton list of iterables. – qaphla Jun 25 '14 at 17:17
1
>>> x =  [(23,5,6,4)]
>>> y = list(x[0])
>>> y
[23, 5, 6, 4]
timgeb
  • 76,762
  • 20
  • 123
  • 145