×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

How to check if list is nested?

How to check if list is nested?

How to check if list is nested?

(OP)
Hi!

How can I check if some list is nested?
I have a list:

CODE

mylist = ['a', 'b', 'c']
then I make a change:

CODE

mylist[0] = ('a1', 'a2')
Now I have nested list:

CODE

[('a1', 'a2'),'b', 'c']
When I want to loop through mylist and print it, I need to check somehow if some list index is nested or not because if yes, printing will be different for nested indexes.

Thanks.

Bosko

RE: How to check if list is nested?

First off, a small nitpick: the square brackets [] are for lists, but the round brackets () are for tuples. As I understand it, tuples are immutable (cannot have their content or structure changed). I bring it up because it affects your solution slightly:

CODE

$ python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['a', 'b', 'c']
>>> mylist[0] = ('a1', 'a2')
>>> mylist
[('a1', 'a2'), 'b', 'c']
>>> if (type(mylist[0]) == tuple):
...     print "do tuple logic"
... elif (type(mylist[0]) == list):
...     print "do list logic"
... else:
...     print "do something else"
do tuple logic

I don't know enough about python to know if this is good form or not, but it does work.

RE: How to check if list is nested?

(OP)
Hi!

Thanks.
This seems to be simplest and shortest way.

B

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login


Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close