Skip to content

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

  • by

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

Syntax

len(list)

Return Value

This method returns the number of items in the list.

Example of get size of list Python

# Python program to demonstrate working
list1 = [10, 20, 30]
n = len(list1)
print("The length of list is: ", n)

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.

a = "Hello, World!"
print(a.len())

Output:

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

Python length of list get size

Right way to do it:-

a = "Hello, World!"
print(len(a))

Output: 13

EMPTY list length

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


list1 = []

print(len(list1))

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.

# empty list
items = []
items.append("apple")
items.append("orange")
items.append("banana")

# Get and print number of elements in the list
print(len(items))

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 the Python length of the Array?

Answer: Python doesn’t have an array data type. Python is using a “List” data type instead of an Array. Both works the 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.

dict1 = {'Name': 'John', 'Age': 72};
print("Length: ", len(dict1))

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

Your email address will not be published. Required fields are marked *