user2155059
user2155059

Reputation: 151

Why does an empty list in python give a length of 3?

When I type in

list = []

print(len(list))

it prints out 3, not 0.

Does anyone know why this is happening?

I'm using python 3.3.

Upvotes: 0

Views: 830

Answers (1)

Lennart Regebro
Lennart Regebro

Reputation: 172239

Well, one way to get that result is the following way:

>>> len = lambda x : 3
>>> print(len(list))
3

To figure out what happened in your case, check what print, len and list are. This is what they should be:

>>> print
<built-in function print>
>>> len
<built-in function len>
>>> list
<class 'list'>
>>> 

Note that you in your example do

>>> list = []

Which is not good practice as you now overwrite one of the built ins. That works, and it's allowed but it can be confusing.

Upvotes: 1

Related Questions