-1

hello I am searching for this solution but couldn't find any

I want to convert below list

list1=[1,2,3,[4],5,[2,4]]

output=[1,2,3,4,5,2,4]

U got it with this code

list1=[1,2,3,[4],5,[2,4]]
list2=[]

for i in range(len(list1)):
    if type(list1[i])!=int:
        for j in range(len(list1[i])):
            list2.append(list1[i][j])
    else:
        list2.append(list1[i])
print(list2)

Can anyone tell any other way to this without for loops and all

rioV8
  • 24,506
  • 3
  • 32
  • 49
  • You could look [here](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) where similar topic has been discussed – baskettaz Jan 07 '22 at 09:20

1 Answers1

-1

That could be a solution. Not the best one, but a solution :

list1 = [1, 2, 3, [4], 5, [2, 4]]
l = []
for i in list1:
    if type(i) is int:
        l.append(i)
    elif type(i) is list:
        for a in i:
            l.append(a)

Better :

list1 = [1, 2, 3, [4], 5, [2, 4]]
l = []
for i in list1:
    if type(i) is int:
        l.append(i)
    elif type(i) is list:
        l.extend(i)
tCot
  • 307
  • 2
  • 7