Linux

How to Find the Length of a List in Python

Lists are one of the most commonly used data types in Python and are used to store collections of items of the same type.

This article shows how to find the length of a list.

len() Function

Python has a built-in function len() that returns the length of a given object. The object can be a list , tuple, string, dictionary, etc.

The syntax of the len() function is as follows:

len(list)

The function accepts only one argument. The returned value is an integer that is the number of elements in the list.

Here is an example:

capitals = ['Tokyo', 'Sofia', 'London', 'Budapest']

list_len = len(capitals)

print("The list has {0} elements.".format(list_len))
Output

The list has 4 elements.

Using Loop

Another way to get the length of a list is to use the for loop. This works by setting up a counter and looping through all the elements of the list. On each iteration, the current value of the counter variable is incremented by one.

Below is a sample code that shows how to find the number of elements in a given list using the for loop:

capitals = ['Tokyo', 'Sofia', 'London', 'Budapest']
counter = 0

for capital in capitals:
counter = counter + 1

print("The list has {0} elements.".format(counter))
Output
The list has 4 elements.

This method is not very Pythonic. You should always prefer using the len() function.

Conclusion

To find the length of a list in Python list, use the len() function.

Rukhsar Malik

Recent Posts

How To Set Up Secure Nginx Server Blocks on Ubuntu 22.04

NGINX Server Nginx, a popular open-source web server, excels at handling high traffic websites efficiently.… Read More

5 days ago

The Web Server Showdown: Nginx vs. Apache, LiteSpeed, Caddy, and Beyond

In the realm of web hosting, choosing the right web server is paramount. It acts… Read More

5 days ago

Linear guidance systems

Are indispensable for ensuring smooth, precise linear motion in many industrial applications. Whether in robotics,… Read More

2 months ago

Cyber Attack Statistics – Identifying Vulnerabilities and Strengthening Defenses

Cyber attacks are becoming more frequent, complex, and damaging. They can disrupt critical operations and… Read More

3 months ago

Empowering Cybersecurity in 2024 with XDR for Comprehensive Threat Detection and Response

With the rise of new threats and the increasing complexity of IT environments, organizations need… Read More

3 months ago

Facade Design Pattern: Simplifying Complex Systems

1. Introduction In software design, managing complex systems can be challenging. The Facade Design Pattern… Read More

5 months ago