Python length of list | Get List size | len() Function

To get the length of the list in python you can use len() function. Len() Function is an inbuilt function in python and returns a number of elements present in the list object.

Syntax

Return Value

This method returns the number of items in the list.

Example of get size of list Python

Output: 3

len() method error if Use it with Python String

You will get an error If you using it like that to get the length of the string in python.

Output:

AttributeError: ‘str’ object has no attribute ‘len’

Python length of list get size

Right way to do it:-

Output: 13

EMPTY list length

If list is empty then len() function will return 0.

Output: 0

Interview Questions

Here are some common interviews questions on get size of list Python.

Q: What is “len function” time complexity?

Answer: len() works in O(1) time as list is an object.

Q: How do I get the number of elements in a list?

Answer: Use python length method “len()” to get the size of list. See below example of it.

Output: 3

Q: What is the best way to find the length of a list in Python?

Answer: The best way to find the length of List in python use Len() function.

Q: How to get Python length of the Array?

Answer: Python doesn’t have a array data type. Python is using a “List” data type instead of Array. Both works same but there are some differences.

Where Array is using in Java, C++ and other programming language and Lists are used in Python.

#Python length of list in dictionary

The following example shows the usage of “len() method” to get Python dict length.

Output: Length: 2

Do comment if you have any questions and suggestions on this tutorial.

Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python Programs code are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.