- Как найти длину списка в Python: инструкция
- Метод len()
- Поиск длины списка с помощью цикла
- Поиск длины списка с помощью рекурсии
- Метод length_hint()
- Заключение
- 3 Ways to Find Python List Size
- What are Lists in Python?
- How to Get the Size of a List in Python?
- 1) Len() method
- Is len() method specific to list data structure?
- 2) Naïve method
- 3) length_hint() method
- Conclusion
- How To Find the Length of a List in Python
- Using the len() method to get the length of a list
- Alternative Ways to Find the Length of a List
- Using the length_hint() method to get the length of a list
- Using a for loop to get the length of a list
- Conclusion
Как найти длину списка в Python: инструкция
Списки в Python используются практически повсеместно. В этом материале мы рассмотрим 4 способа как найти длину списка Python : с помощью встроенных функций, рекурсии и цикла. Длина списка чаще всего используется для перемещения по списку и выполнения с ним различных операций.
Метод len()
len() — встроенный метод Python для нахождения длины списка. На вход метод принимает один параметр: сам список. В качестве результата len() возвращает целочисленное значение — длину списка. Также этот метод работает и с другими итеративными объектами, например со строками.
Country_list = ["The United States of America", "The Russian Federation", "France", "Germany"]count = len(Country_list)
print("There are", count, "countries")
Поиск длины списка с помощью цикла
Длину списка можно узнать с помощью цикла for . Для этого необходимо пройти по всему списку, увеличивая счетчик на 1 за каждую итерацию. Определим для этого отдельную функцию:
def list_length(list):
counter = 0
for i in list:
counter=counter+1
return counter
Country_list = ["The United States of America", "The Russian Federation", "France", "Germany","Japan"]count = list_length(Country_list)
print("There are", count, "countries")
Поиск длины списка с помощью рекурсии
Задачу поиска длины списка можно решить с помощью рекурсии. Вот код:
def list_length_recursive(list):
if not list:
return 0
return 1 + list_length_recursive(list[1:])
Country_list = ["The United States of America", "The Russian Federation", "France", "Germany","Japan","Poland"]count = list_length_recursive(Country_list)
print("There are", count, "countries")
Как это работает. На вход в функцию list_length_recursive() поступает список. Если он не содержит элементов, то возвращает 0 — длина пустого списка равна нулю. Если в нём есть элементы, то он вызывает рекурсивную функцию с аргументов list[1:] — срезом исходного списка с 1 элемента, т.е. списком без элемента на 0 индексе. Результат работы этой функции прибавляется к 1. За каждую рекурсию result увеличивается на единицу, а список уменьшается на 1 элемент.
Метод length_hint()
Метод length_hint() относится к модулю operator . В модуль operator включены функции, аналогичные внутренним операторам Python: сложению, вычитанию, сравнению и т.п. Метод length_hint() возвращает длину итеративных объектов: строк, кортежей, словарей и списков. Работает length_hint() аналогично методу len() :
from operator import length_hint
Country_list = ["The United States of America", "The Russian Federation", "France", "Germany", "Japan", "Poland", "Sweden"]count = length_hint(Country_list)
print("There are", count, "countries")
Для работы с length_hint() его необходимо импортировать.
Заключение
В рамках этого материала мы рассмотрели 4 способа нахождения длины списка в Python. Наиболее оптимальным методом при прочих равных является len() . Сложность его работы равна O(1) и применение остальных методов оправдано для реализации собственных классов наподобие list . Если вы хотите изучить Python глубже, то читайте другие наши публикации на тему работы с Python, а также арендуйте облачные серверы на timeweb.cloud для реализации своих проектов и экспериментов с этим языком.
3 Ways to Find Python List Size
Python is one of the fundamental programming languages widely used in the machine learning and artificial intelligence domain. Python possesses various data structures which help you to deal with data effectively and efficiently. The list is one of the sequential data structures in python that is highly used to store data collection and operate on it. In this article, let us study how to find python list size with 3 methods and examples in detail. But before that, let us have a brief introduction to a list data structure in python below.
What are Lists in Python?
List in python is used to store the multiple elements in a single variable. List elements are ordered, changeable, and also allow duplicate values. Hence, Python lists are mutable, which means that you can modify the elements of the lists after they are created. For initiating the list, you have to insert elements inside the square brackets ([]), each element separated by a comma (,) in between. To learn more about lists, visit our article “3 Ways to Convert Lists to Tuple”.
For example:
sample_list = ['Programming', 'with', 'Favtutor']; print(sample_list)
['Programming', 'with', 'Favtutor']
How to Get the Size of a List in Python?
There are 3 methods by which you can find the size of lists in python. Let us learn all of those methods in detail below:
1) Len() method
The best way to find the total number of elements in the list is by using the len() method. The len() method accepts the lists as an argument and returns the number of elements present. Below is the syntax of the len() method:
According to programmers, len() is the most convenient method to get the size of the list in python. The len() method works in O(1) time as a list is an object and needs memory to store its size.
Check out the below example to understand the working of len() method in detail:
For example:
sample_list = ['Programming', 'with', 'Favtutor']; list_size = len(sample_list) print(list_size)
Is len() method specific to list data structure?
No, len() method is not specifically used to find the size of the list data structure. Programmers also use other data structures like arrays, tuples, and sets while programming in python and often face difficulty finding its length for a different purpose. Therefore, you can use the len() method to get the size of almost all the data structures or collections, such as dictionaries. Using the len() method, you can also get the length of a total number of elements inside the set and frozenset.
2) Naïve method
Other than len() method, you can also loop to find the size of lists in python. In this naïve method, you have to run the loop and increase the counter variable after traversing the element in lists. At last, when the pointer becomes empty, the value stored inside the counter variable is the size of the list. This method is most efficient if you are not available with any other technique. Talking about the basic algorithm, check out the below steps to find the length of the list:
- Declare the counter variable and assign zero to it.
- Using for loop, traverse the elements of the list, and after every element, increment the counter variable by +1.
- Hence, the length of the lists will be stored in the counter variable, and you can return it by representing the counter variable.
For example:
sample_list = ['Programming', 'with', 'Favtutor']; counter = 0 for i in sample_list: counter = counter+1 print(counter)
3) length_hint() method
Python has an in-built operator named length_hint() to find the size of the lists. Not only lists, but you can also use this method to find the length of tuples, sets, dictionaries and any other python data structure. The operator.length.hint() method takes the variable as a parameter in which the data is stored. Note that this is the least used method to find the length of data structure as it is only applicable in python programming. Moreover, you have to import the lenght_hint method from the in-built operator library using the «import» keyword, just like shown in the below example:
For example:
from operator import length_hint sample_list = ['Programming', 'with', 'Favtutor'] list_size = length_hint(sample_list) print(list_size)
Conclusion
Lists in python are a primary data structure, highly used to store the sequential data inside a single variable. At the same time, the information on measuring the size of a list in python is one of the most basic operations that you must know as a programmer. Therefore, we have mentioned the three common methods to find the size of the lists in python with examples and their respective output. It is highly recommended to learn and understand them for making your programming efficient and faster.
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.