Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to check if list is nested?

Status
Not open for further replies.

bokula

Programmer
May 18, 2007
5
0
0
SK
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
 
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.
 
Hi!

Thanks.
This seems to be simplest and shortest way.

B
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top