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]}]
l3=[]
for i in (l2):
if type(i)==list:
l3.append(i)
print(l3)
Output
[]
[]
[]
[]
[]
[[23, 456, 67, 8, 78, 78]]
[[23, 456, 67, 8, 78, 78], [345, 56, 87, 8, 98, 9]]
[[23, 456, 67, 8, 78, 78], [345, 56, 87, 8, 98, 9]]
[[23, 456, 67, 8, 78, 78], [345, 56, 87, 8, 98, 9]]
Can anyone please tell me why am I getting empty lists and repeated output while appending the list?
CodePudding user response:
As previous comments point out you've made mistake of putting print inside the for-loop, it's easy fix. Also it's better to use ininstance here instead.
It's even better to just use List Comprehension like this to speed up and easy to read:
Note - Credits to earlier posts, here it's a summary for the record.
# Orig.
for item in (l2):
if isinstance(item, list): # only extract list
l3.append(item)
# when all is done
print(l3)
# List Comprehension:
new_lst = [lst for lst in l2 if isinstance(lst, list)]
assert l3 == new_lst # Silence - they're same