Get list length in python

Python List Length – How to Get the Size of a List in Python

Kolade Chris

Kolade Chris

Python List Length – How to Get the Size of a List in Python

In Python, you use a list to store various types of data such as strings and numbers.

A list is identifiable by the square brackets that surround it, and individual values are separated by a comma.

To get the length of a list in Python, you can use the built-in len() function.

Apart from the len() function, you can also use a for loop and the length_hint() function to get the length of a list.

In this article, I will show you how to get the length of a list in 3 different ways.

How to Get the Length of a List in Python with a For Loop

You can use the native for loop of Python to get the length of a list because just like a tuple and dictionary, a list is iterable.

This method is commonly called the naïve method.

The example below shows you how to use the naïve method to get the length of a list in Python

demoList = ["Python", 1, "JavaScript", True, "HTML", "CSS", 22] # Initializing counter variable counter = 0 for item in demoList: # Incrementing counter variable to get each item in the list counter = counter + 1 # Printing the result to the console by converting counter to string in order to get the number print("The length of the list using the naive method is: " + str(counter)) # Output: The length of the list using the naive method is: 7 

How to Get the Length of a List with the len() Function

Using the len() function is the most common way to get the length of an iterable.

This is more straightforward than using a for loop.

The syntax for using the len() method is len(listName) .

The code snippet below shows how to use the len() function to get the length of a list:

demoList = ["Python", 1, "JavaScript", True, "HTML", "CSS", 22] sizeOfDemoList = len(demoList) print("The length of the list using the len() method is: " + str(sizeOfDemoList)) # Output: The length of the list using the len() method is: 7 

How to Get the Length of a List with the length_hint() Function

The length_hint() method is a less known way of getting the length of a list and other iterables.

length_hint() is defined in the operator module, so you need to import it from there before you can use it.

The syntax for using the length_hint() method is length_hint(listName) .

The example below shows you how to use the length_hint() method to get the length of a list:

from operator import length_hint: demoList = ["Python", 1, "JavaScript", True, "HTML", "CSS", 22] sizeOfDemoList = length_hint(demoList) print("The length of the list using the length_hint() method is: " + str(sizeOfDemoList)) # The length of the list using the length_hint() method is: 7 

Final Thoughts

This article showed you how to get the size of a list with 3 different methods: a for loop, the len() function, and the length_hint() function from the operator module.

Читайте также:  What is javascript html dom

You might be wondering which to use between these 3 methods.

I would advise that you use len() because you don’t need to do much to use it compared to for loop and length_hint() .

In addition, len() seems to be faster than both the for loop and length_hint() .

If you find this article helpful, share it so it can reach others who need it.

Источник

Python List Length or Size: 5 Ways to Get Length of List

Python Get Length of List Cover Image

In this tutorial, you’ll learn how to use Python to get the length of a list (or, rather, its size). Knowing how to work with lists is an important skill for anyone using Python. Being able to get a Python list length, is particularly helpful. You’ll learn how to get the Python list length using both the built-in len() function, a naive implementation for-loop method, how to check if a list is empty, and how to check the length of lists of lists.

The Quick Answer: Use len() to get the Python list length

Quick answer to get the length of a Python list

Python List Length using the len() function

The easiest (and most Pythonic) way to use Python to get the length or size of a list is to use the built-in len() function. The function takes an iterable object as its only parameter and returns its length.

Let’s see how simple this can really be:

# Get the length of a Python list a_list = [1,2,3,'datagy!'] print(len(a_list)) # Returns: 4

We can see here that by using the len() function, we can easily return the length of a Python list.

In the next section you’ll learn how to use a for-loop naive implementation to get the size of a Python list.

Python List Length using a for-loop

While this approach is not recommended (definitely use the method above!), this for-loop method does allow us to understand an algorithm in terms of counting items in an iterable.

In order to do this, we iterate over each item in the list and add to a counter. Let’s see how we can accomplish this in Python:

# Get the length of a Python list a_list = [1,2,3,'datagy!'] length = 0 for _ in a_list: length += 1 print(length) # Returns 4

This approach certainly isn’t as straightforward as using the built-in len() function, but it does explain some algorithmic thinking around counting items in Python.

In the next section, you’ll learn how to easily check if a Python list is empty or not empty.

Want to learn more about Python for-loops? Check out my in-depth tutorial on Python for loops to learn all you need to know!

Check if a Python list is empty or not empty

In your programming journey, you’ll often encounter situations where you need to determine if a Python list is empty or not empty.

Now that you know how to get the length of a Python list, you can simply evaluate whether or not the length of a list is equal to zero or not:

# How to check if a Python list is empty a_list = [] if len(a_list) != 0: print("Not empty!") else: print("Empty!") # Returns: Empty!

But Python makes it actually much easier to check whether a list is empty or not. Because the value of 0 actually evaluates to False , and any other value evaluates to True , we can simply write the following:

# An easier way to check if a list is empty a_list = [] if a_list: print("Not empty!") else: print("Empty!") # Returns: Empty!

This is much cleaner in terms of writing and reading your code.

Читайте также:  Instantiated example in java

In the next section, you’ll learn how to get the length of Python lists of lists.

Learn to split a Python list into different-sized chunks, including how to turn them into sublists of their own, using this easy-to-follow tutorial.

Get Length of Python List of Lists

Working with Python lists of lists makes getting their length a little more complicated.

To better explain this, let’s take a look at an immediate example:

# Get the length of a list of lists a_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] print(len(a_list_of_lists)) # Returns: 3

We can see here, that the code (correctly) returns 3 . But what if we wanted to get the length of the all the items contained in the outer list?

In order to accomplish this, we can sum up the lengths of each individual list by way of using a Python list comprehension and the sum function.

Let’s see how this can be done:

# Get the length of a list of lists a_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] length = sum([len(sub_list) for sub_list in a_list_of_lists]) print(length) # Returns: 9

Finally, let’s see how we can use Python to get the length of each list in a list of lists.

Want to learn more about Python list comprehensions? This in-depth tutorial will teach you all you need to know. More of a visual learner? A follow-along video is also included!

Get Length of Each List in a Python List of Lists

In the example above, you learned how to get the length of all the items in a Python list of lists. In this section, you’ll learn how to return a list that contains the lengths of each sublist in a list of lists.

We can do this, again, by way of a Python list comprehension. What we’ll do, is iterate over each sublist and determine its length. A keen eye will notice it’s the same method we applied above, simply without the sum() function as a prefix.

Let’s take a look at how to do this:

# Get the length of each sublist in a list of lists a_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] lengths = [len(sublist) for sublist in a_list_of_lists] print(lengths) # Returns [3, 3, 3]

In this section, you learned how to use Python to get the length of each sublist in a list of lists.

Want to learn how to append items to a list? This tutorial will teach your four different ways to add items to your Python lists.

Conclusion

In this post, you learned how to use Python to calculate the length of a list. You also learned how to check if a Python list is empty or not. Finally, you learned how to calculate the length of a list of lists, as well as how to calculate the length of each list contained within a list of lists.

To learn more about the Python len() function, check out the official documentation here.

Источник

How To Find the Length of a List in Python

How To Find the Length of a List in Python

There are several techniques you can use in Python to find the length of a list. The length of a list is the number of elements in the list. This article describes three ways to find the length of a list, however, the len() method is usually the best approach to get the length of a list because it’s the most efficient. Since a list is an object, the size of the list if already stored in memory for quick retrieval.

Using the len() method to get the length of a list

You can use the built-in len() method to find the length of a list.

The len() method accepts a sequence or a collection as an argument and returns the number of elements present in the sequence or collection.

Читайте также:  Форма обратной связи

The following example provides a list and uses the len() method to get the length of the list:

inp_lst = ['Python', 'Java', 'Ruby', 'JavaScript'] size = len(inp_lst) print(size) 

Alternative Ways to Find the Length of a List

Although the len() method is usually the best approach to get the length of a list because it’s the most efficient, there are a few other ways to find the length of a list in Python.

Using the length_hint() method to get the length of a list

The Python operator module has a length_hint() method to estimate the length of a given iterable object. If the length is known, the length_hint() method returns the actual length. Otherwise, the length_hint() method returns an estimated length. For lists, the length is always known, so you would normally just use the len() method.

The syntax of length_hint() is:

The following example provides a list and uses the length_hint() method to get the length of the list:

from operator import length_hint inp_lst = ['Python', 'Java', 'Ruby', 'JavaScript'] size = length_hint(inp_lst) print(size) 

Using a for loop to get the length of a list

This section provides a less practical, but still informative, way of finding the length of a list with no special method. Using a for loop to get the list length is also known as the naive method and can be adapted for use in almost any programming language.

The basic steps to get the length of a list using a for loop are:

    Declare a counter variable and initialize it to zero.

for item in list: counter += 1 

The following example demonstrates how to get the length of a list:

inp_lst = ['Python', 'Java', 'Ruby', 'JavaScript'] size = 0 for x in inp_lst: size += 1 print(size) 

Conclusion

In this article, you learned some different ways to find the length of a list in Python. Continue your learning with more Python tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Python – Find list length

Python List Length represents the number of elements in the list.

To get the length of list in Python, call the python global function len() with the list passed as argument.

You could also use looping statements, like for loop or while loop, to find the number of elements in a list. But, that would become inefficient, since we have inbuilt function.

Syntax

The syntax of len() function to find the list length is as shown below.

The function returns an integer which represents number of items present in the list.

Examples

1. Length of a given list

In the following example, we will create a list and then use the len() builtin function to find the number of items in it.

Python Program

#a list cars = ['Ford', 'Volvo', 'BMW', 'Tesla'] #find length of list length = len(cars) print('Length of the list is :', length)

There are four elements in the list, hence a length of 4.

2. Length of a list (with list updates)

In the following example, we will create a list and then add or remove some elements from the list, and find the resulting length.

Python Program

#a list cars = ['Ford', 'Volvo', 'BMW', 'Tesla'] #some updates on list cars.append('Honda') cars.append('Tata') #find length of list length = len(cars) print('Length of the list is :', length)

Initially, there are four elements in the list. Later we added to elements using list append(). Therefore the final length of the list became six.

Summary

In this tutorial of Python Examples, we learned how to find length of a given list using len() builtin function.

Источник

Оцените статью