Amit Ahire
Amit Ahire

Reputation: 313

How does len count in list?

Ok I tried searching before I posted here. So don't shot me down if its already asked.

I want to know in Python's len function.

len([o,1]) -> 2 # Right

But how come in the following

len([a,[b,[c]]]) -> 2 # How?

Shouldn't it be 3??

I know this could be a very trivial question. So again please be patient with it.

Upvotes: 0

Views: 200

Answers (4)

Matt Dawdy
Matt Dawdy

Reputation: 19717

As others said, you have a list with 2 elements (a and [b,[c]]). If you wanted a list with 3 elements, you would use [a,b,c].

Upvotes: 0

Paul Karlin
Paul Karlin

Reputation: 840

This is because [a,[b,[c]]] is a nested list. The first element of the outer list is a, and the second is [b,[c]].

Upvotes: 4

Doug T.
Doug T.

Reputation: 65599

Shouldn't it be 3??

No because

[a,[b,[c]]]

is a two element list the first element is "a"

a

the second element is a list

[b,[c]]

(a list, itself len of 2 that contains yet another list of len 1).

Upvotes: 3

Gangadhar
Gangadhar

Reputation: 1903

First of all, welcome to StackOverflow. And coming to your question - len calculates the length of the list. So, in your example, the list has two elements a and another list [b,[c]]. If you were to find the length of the inner list it is again two since it has two elements.

Upvotes: 0

Related Questions