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] ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With