-1

How would you loop through each element in a list in python. For example if I have the list:

list = ["abc",3,(10,(11,12))]

I would like to have the split up the list into: ['a','b','c',3,10,11,12]

Right now I have:

def combinelist(list):
   l = []
   for item in list:
      l.append(item)
    return l

However this just returns the exact same list. How would I go thorough each element in the list and split each element? Thanks for the help!

user3750474
  • 249
  • 5
  • 18
  • @Michael0x2a not quite, what the OP shows isn't a list of iterables (you can't iterate over `3`) – David Robinson Sep 10 '14 at 04:08
  • @DavidRobinson - ah, you're right. I didn't see that. – Michael0x2a Sep 10 '14 at 04:09
  • I think you wanted `extend`, not `append` here. `lst.append([1,2,3])` will add the list `[1,2,3]` to the end, but `lst.extend([1,2,3])` will add the three separate values `1`, `2`, and `3` to the end. However, that will raise an exception when you try it on `3`, and it will only flatten `(10,(11,12))` into the two values `10` and `(11,12)`. That's why the answers in the linked question all either use recursion or a loop. – abarnert Sep 10 '14 at 04:26

1 Answers1

1

Well, I don't know elegant way to code it, so...

l = ["abc",3,('x','y')]

o = []
for i in l:
    if isinstance(i, str):
        o.extend(list(i))
    elif isinstance(i, (tuple, list)):
        o.extend(i)
    else:
        o.append(i)

print o

Or:

o = []
for i in l:
    try:
        o.extend(list(i)) # can it be casted to sequence?
    except TypeError:
        o.append(i)
print o

Or even:

o = []
for i in l:
    if isinstance(i, (str, list, tuple)):
        o.extend(list(i)) 
    else:
        o.append(i)
print o
felipsmartins
  • 13,269
  • 4
  • 48
  • 56