3

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)
1
  • Please show your desired output. Is it ['sally','joe'] or is it joe mike sally joe phil (with newlines between)? Commented Nov 20, 2018 at 2:18

2 Answers 2

2

Why not just isinstance:

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

Now the output is:

['sally', 'joe']
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Downvoter: Care to comment? This answer was supposed to be "what went wrong?" and not "what's the right way".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.