Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested List Loop

I would like to loop the nest list ['sally','joe'] in the example shown below.

data = ['joe','mike',['sally','joe'],'phil']

I attempted the following:

for i in data:
    for j in (i):
        if type(j) == '<class '+"'list'>":    
            print(j)
like image 554
Zach Avatar asked Mar 12 '26 04:03

Zach


2 Answers

Why not just isinstance:

for i in data:
    if isinstance(i,list):
        print(i)

Now the output is:

['sally', 'joe']
like image 87
U12-Forward Avatar answered Mar 14 '26 17:03

U12-Forward


You would need to use:

if type(j) == list:
    print(j)

It doesn't currently work because type(j) returns an object of class type, not a string. You might think it is a string because when printing it in a REPL interpreter, you might see the repr(..) version.

like image 44
UltraInstinct Avatar answered Mar 14 '26 18:03

UltraInstinct