Home > Software engineering >  I am trying to extract nested list. Am I coding wrong?
I am trying to extract nested list. Am I coding wrong?

Time:07-21

I am trying to extract nested list. Am I coding wrong?

l2=[3,4,5,6,7, [23,456,67,8,78,78], [345,56,87,8,98,9], (234,6657,6), {'key1': "sudh",234:[23,45,656]}]

for i in l2:
    if i==list:
        break

print (l2[i])

--------------------Out Put-----------------------

{'key1': "sudh",234:[23,45,656]}

CodePudding user response:

Please add expected output in your question
As mentioned in question you need to check type and not it's value you can do as mentioned below:

l2=[3,4,5,6,7, [23,456,67,8,78,78], [345,56,87,8,98,9], (234,6657,6), {'key1': "sudh",234:[23,45,656]}]

for i in l2:
    if type(i)==list:
        print(i)
# OR
for i in l2:
    if isinstance(i,list):
        print(i)

Output:

[23, 456, 67, 8, 78, 78]
[345, 56, 87, 8, 98, 9]

PS: for i in l2 is iterating over it's element and it's not some index so you cannot use it as index in l2[i] as i is the element and not index

  • Related