Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding nested lists in Python

I am having a bit of trouble understanding what a one-level list, two-level list and a three-level list is. I want to just eye-ball it and know it is one or the other, but I am getting confused with the brackets.

What defines levels in a list?

Is this considered a three-level list?

​[ [[5,6],7], 9]

Or is this a three-level list?

​[ [7,2], [[2,3],4], [[[5,6],7],9] ]
like image 889
Helloimjs0n Avatar asked Feb 03 '26 16:02

Helloimjs0n


1 Answers

The concept of nested lists is not terribly complicated, it just means that you can have a list inside of a list. In that list, you could have another list, and so on.

The terms one-level, two-level or n-level list are not widely used, it is more common to use the term nesting level. So let's write a small algorithm to visualize nesting levels:

>>> def nestprint(lst, level=0):
...     print('{} is at nesting level {}'.format(lst, level))
...     for item in lst:
...         if isinstance(item, list):
...             nestprint(item, level+1)

For a given list, this will print out the nesting level of each list. Here is what it does for your examples:

>>> nestprint([[[5,6],7],9])
[[[5, 6], 7], 9] is at nesting level 0
[[5, 6], 7] is at nesting level 1
[5, 6] is at nesting level 2
>>>    
>>> nestprint([[7,2],[[2,3],4],[[[5,6],7],9]])
[[7, 2], [[2, 3], 4], [[[5, 6], 7], 9]] is at nesting level 0
[7, 2] is at nesting level 1
[[2, 3], 4] is at nesting level 1
[2, 3] is at nesting level 2
[[[5, 6], 7], 9] is at nesting level 1
[[5, 6], 7] is at nesting level 2
[5, 6] is at nesting level 3

Hopefully this clears things up for you.

like image 156
timgeb Avatar answered Feb 05 '26 07:02

timgeb