Как найти длину списка пайтон

Список

Назад в начало

Список – это непрерывная динамическая коллекция элементов. Каждому элементу списка присваивается порядковый номер – его индекс. Первый индекс равен нулю, второй – единице и так далее. Основные операции для работы со списками – это индексирование, срезы, добавление и удаление элементов, а также проверка на наличие элемента в последовательности.

Создание пустого списка выглядит так:

empty_list = []

Создадим список, состоящий из нескольких чисел:

numbers = [40, 20, 90, 11, 5]

Настало время строковых переменных:

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

Не будем забывать и о дробях:

fractions = [3.14, 2.72, 1.41, 1.73, 17.9]

Мы можем создать список, состоящий из различных типов данных:

values = [3.14, 10, ‘Hello world!’, False, ‘Python is the best’]

И такое возможно (⊙_⊙)

list_of_lists = [[2, 4, 0], [11, 2, 10], [0, 19, 27]]

Индексирование

Что же такое индексирование? Это загадочное слово обозначает операцию обращения к элементу по его порядковому номеру ( ( ・ω・)ア напоминаю, что нумерация начинается с нуля). Проиллюстрируем это на примере:

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

print(fruits[0])

print(fruits[1])

print(fruits[4])

>>> Apple

>>> Grape

>>> Orange

Списки в Python являются изме­няемым типом данных. Мы можем изменять содер­жимое каждой из ячеек:

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

fruits[0] = ‘Watermelon’

fruits[3] = ‘Lemon’

print(fruits)

>>> [‘Watermelon’, ‘Grape’, ‘Peach’, ‘Lemon’, ‘Orange’]

Индексирование работает и в обратную сторону. Как такое возможно? Всё просто, мы обра­щаемся к элементу списка по отрица­тельному индексу. Индекс с номе­ром -1 дает нам доступ к после­днему элементу, -2 к предпоследнему и так далее.

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

print(fruits[-1])

print(fruits[-2])

print(fruits[-3])

print(fruits[-4])

>>> Orange

>>> Banan

>>> Peach

>>> Grape

Создание списка с помощью list()

Переходим к способам создания списка. Самый простой из них был приведен выше. Еще раз для закрепления:

smiles = [‘(ಠ_ಠ)’, ‘( ̄﹃ ̄)’, ‘( ͡° ͜ʖ ͡°)’, ‘(╮°-°)╮’]

А есть еще способы? Да, есть. Один из них — создание списка с помощью функции list() В неё мы можем передать любой итерируемый объект (да-да, тот самый по которому можно запустить цикл (• ᵕ •) )

Рассмотрим несколько примеров:

letters = list(‘abcdef’)

numbers = list(range(10))

even_numbers = list(range(0, 10, 2))

print(letters)

print(numbers)

print(even_numbers)

>>> [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’

>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> [0, 2, 4, 6, 8]

Длина списка

С созданием списка вроде ра­зобрались. Следующий вопрос: как узнать длину списка? Можно, конечно, просто посчитать количество элементов… (⊙_⊙) Но есть способ получше! Функция len() возвращает длину любой итерируемой переменной, переменной, по которой можно запустить цикл. Рассмотрим пример:

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

print(len(fruits))

>>> 5

numbers = [40, 20, 90]

print(len(numbers))

>>> 3

“…любой итерируемой”, а это значит:

string = ‘Hello world’

print(len(string))

# 11

>>> 11

print(len(range(10))

>>> 10

Срезы

В начале статьи что-то гово­рилось о “срезах”. Давайте разберем подробнее, что это такое. Срезом называется неко­торая подпос­ледователь­ность. Принцип действия срезов очень прост: мы “отре­заем” кусок от исходной последова­тель­ности элемента, не меняя её при этом. Я сказал “последо­вательность”, а не “спи­сок”, потому что срезы работают и с другими итерируемыми типами данных, например, со строками.

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

part_of_fruits = fruits[0:3]

print(part_of_fruits)

>>> [‘Apple’, ‘Grape’, ‘Peach’]

Детально рассмотрим синтаксис срезов:

итерируемая_переменная[начальный_индекс:конечный_индекс 1:длина_шага]

Обращаю ваше внимание, что мы делаем срез от начального индекса до конечного индекса – 1. То есть i = начальный_индекс и i < конечный индекс

Больше примеров!

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

print(fruits[0:1])

# Если начальный индекс равен 0, то его можно опустить

print(fruits[:2])

print(fruits[:3])

print(fruits[:4])

print(fruits[:5])

# Если конечный индекс равен длине списка, то его тоже можно опустить

print(fruits[:len(fruits)])

print(fruits[::])

>>> [‘Apple’]

>>> [‘Apple’, ‘Grape’]

>>> [‘Apple’, ‘Grape’, ‘Peach’]

>>> [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’]

>>> [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

>>> [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

>>> [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

Самое время понять, что делает третий параметр среза – длина шага!

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

print(fruits[::2])

print(fruits[::3])

# Длина шага тоже может быть отрицательной!

print(fruits[::-1])

print(fruits[4:2:-1])

print(fruits[3:1:-1])

>>> [‘Apple’, ‘Peach’, ‘Orange’]

>>> [‘Apple’, ‘Banan’]

>>> [‘Orange’, ‘Banan’, ‘Peach’, ‘Grape’, ‘Apple’]

>>> [‘Orange’, ‘Banan’]

>>> [‘Banan’, ‘Peach’]

А теперь вспоминаем всё, что мы знаем о циклах. В Python их целых два! Цикл for и цикл while Нас интересует цикл for, с его помощью мы можем перебирать зна­чения и индексы наших последовательностей. Начнем с перебора значений:

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

for fruit in fruits:

    print(fruit, end=‘ ‘)

>>> Apple Grape Peach Banan Orange

Выглядит несложно, правда? В переменную fruit объявлен­ную в цикле по очереди записываются значения всех элементов списка fruits

А что там с перебором индексов?

for index in range(len(fruits)):

    print(fruits[index], end=‘ ‘)

Этот пример гораздо интереснее предыдущего! Что же здесь происходит? Для начала разбе­ремся, что делает функция range(len(fruits))

Мы с вами знаем, что функция len() возвращает длину списка, а range() генерирует диапазон целых чисел от 0 до len()-1.

Сложив 2+2, мы получим, что переменная index принимает значения в диапазоне от 0 до len()-1. Идем дальше, fruits[index] – это обращение по индексу к элементу с индексом index списка fruits. А так как переменная index принимает значения всех индексов списка fruits, то в цикле мы переберем значения всех элементов нашего списка!

Операция in

С помощью in мы можем проверить наличие элемента в списке, строке и любой другой итерируемой переменной.

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

if ‘Apple’ in fruits:

    print(‘В списке есть элемент Apple’)

>>> В списке есть элемент Apple

fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

if ‘Lemon’ in fruits:

    print(‘В списке есть элемент Lemon’)

else:’

    print(‘В списке НЕТ элемента Lemon’)

>>> В списке НЕТ элемента Lemon

Приведу более сложный пример:

all_fruits = [‘Apple’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Orange’]

my_favorite_fruits = [‘Apple’, ‘Banan’, ‘Orange’]

for item in all_fruits:

    if item in my_favorite_fruits:

        print(item + ‘ is my favorite fruit’)

    else:

        print(‘I do not like ‘ + item)

>>> Apple is my favorite fruit

>>> I do not like Grape

>>> I do not like Peach

>>> Banan is my favorite fruit

>>> Orange is my favorite fruit

Методы для работы со списками

Начнем с метода append(), который добавляет элемент в конец списка:

# Создаем список, состоящий из четных чисел от 0 до 8 включительно

numbers = list(range(0,10,2))

# Добавляем число 200 в конец списка

numbers.append(200)

numbers.append(1)

numbers.append(2)

numbers.append(3)

print(numbers)

>>> [0, 2, 4, 6, 8, 200, 1, 2, 3]

Мы можем передавать методу append() абсолютно любые значения:

all_types = [10, 3.14, ‘Python’, [‘I’, ‘am’, ‘list’]]

all_types.append(1024)

all_types.append(‘Hello world!’)

all_types.append([1, 2, 3])

print(all_types)

>>> [10, 3.14, ‘Python’, [‘I’, ‘am’, ‘list’], 1024, ‘Hello world!’, [1, 2, 3]]

Метод append() отлично выпол­няет свою функцию. Но, что делать, если нам нужно добавить элемент в сере­дину списка? Это умеет метод insert(). Он добавляет элемент в список на произ­вольную позицию. insert() принимает в качестве первого аргу­мента позицию, на которую нужно вставить элемент, а вторым — сам элемент.

# Создадим список чисел от 0 до 9

numbers = list(range(10))

# Добавление элемента 999 на позицию с индексом 0

numbers.insert(0, 999)

print(numbers) # первый print

numbers.insert(2, 1024)

print(numbers) # второй print

numbers.insert(5, ‘Засланная строка-шпион’)

print(numbers) # третий print

>>> [999, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # первый print

>>> [999, 0, 1024, 1, 2, 3, 4, 5, 6, 7, 8, 9] # второй print

>>> [999, 0, 1024, 1, 2, ‘Засланная строка-шпион’, 3, 4, 5, 6, 7, 8, 9] # третий print

Отлично! Добавлять элементы в список мы научи­лись, осталось понять, как их из него удалять. Метод pop() удаляет эле­мент из списка по его индексу:

numbers = list(range(10))

print(numbers) # 1

# Удаляем первый элемент

numbers.pop(0)

print(numbers) # 2

numbers.pop(0)

print(numbers) # 3

numbers.pop(2)

print(numbers) # 4

# Чтобы удалить последний элемент, вызовем метод pop без аргументов

numbers.pop()

print(numbers) # 5

numbers.pop()

print(numbers) # 6

>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 1

>>> [1, 2, 3, 4, 5, 6, 7, 8, 9] # 2

>>> [2, 3, 4, 5, 6, 7, 8, 9] # 3

>>> [2, 3, 5, 6, 7, 8, 9] # 4

>>> [2, 3, 5, 6, 7, 8] # 5

>>> [2, 3, 5, 6, 7] # 6

Теперь мы знаем, как удалять элемент из списка по его инде­ксу. Но что, если мы не знаем индекса элемента, но знаем его значение? Для такого случая у нас есть метод remove(), кото­рый удаляет пер­вый найденный по значению элемент в списке.

all_types = [10, ‘Python’, 10, 3.14, ‘Python’, [‘I’, ‘am’, ‘list’]]

all_types.remove(3.14)

print(all_types) # 1

all_types.remove(10)

print(all_types) # 2

all_types.remove(‘Python’)

print(all_types) # 3

>>> [10, ‘Python’, 10, ‘Python’, [‘I’, ‘am’, ‘list’]] # 1

>>> [‘Python’, 10, ‘Python’, [‘I’, ‘am’, ‘list’]] # 2

>>> [10, ‘Python’, [‘I’, ‘am’, ‘list’]] # 3

А сейчас немного посчитаем, посчитаем эле­менты списка с помощью метода count()

numbers = [100, 100, 100, 200, 200, 500, 500, 500, 500, 500, 999]

print(numbers.count(100)) # 1

print(numbers.count(200)) # 2

print(numbers.count(500)) # 3

print(numbers.count(999)) # 4

>>> 3 # 1

>>> 2 # 2

>>> 5 # 3

>>> 1 # 4

В программировании, как и в жизни, проще работать с упоря­доченными дан­ными, в них легче ори­енти­ро­ваться и что-либо искать. Метод sort() сорти­рует список по воз­раста­нию значений его элементов.

numbers = [100, 2, 11, 9, 3, 1024, 567, 78]

numbers.sort()

print(numbers) # 1

fruits = [‘Orange’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Apple’]

fruits.sort()

print(fruits) # 2

>>> [2, 3, 9, 11, 78, 100, 567, 1024] # 1

>>> [‘Apple’, ‘Banan’, ‘Grape’, ‘Orange’, ‘Peach’] # 2

Мы можем изменять порядок сортировки с помощью пара­метра reverse. По умол­чанию этот параметр равен False

fruits = [‘Orange’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Apple’]

fruits.sort()

print(fruits) # 1

fruits.sort(reverse=True)

print(fruits) # 2

>>> [‘Apple’, ‘Banan’, ‘Grape’, ‘Orange’, ‘Peach’] # 1

>>> [‘Peach’, ‘Orange’, ‘Grape’, ‘Banan’, ‘Apple’] # 2

Иногда нам нужно перевернуть список, не спраши­вайте меня зачем… Для этого в самом лучшем языке прог­рам­миро­вания на этой планете JavaScr..­Python есть метод reverse():

numbers = [100, 2, 11, 9, 3, 1024, 567, 78]

numbers.reverse()

print(numbers) # 1

fruits = [‘Orange’, ‘Grape’, ‘Peach’, ‘Banan’, ‘Apple’]

fruits.reverse()

print(fruits) # 2

>>> [78, 567, 1024, 3, 9, 11, 2, 100] # 1

>>> [‘Apple’, ‘Banan’, ‘Peach’, ‘Grape’, ‘Orange’] # 2

Допустим, у нас есть два списка и нам нужно их объединить. Програм­мисты на C++ cразу же кинулись писать циклы for, но мы пишем на python, а в python у спис­ков есть полез­ный метод extend(). Этот метод вызы­вается для одного списка, а в качестве аргу­мента ему пере­дается другой список, extend() запи­сывает в конец первого из них начало вто­рого:

fruits = [‘Banana’, ‘Apple’, ‘Grape’]

vegetables = [‘Tomato’, ‘Cucumber’, ‘Potato’, ‘Carrot’]

fruits.extend(vegetables)

print(fruits)

>>> [‘Banana’, ‘Apple’, ‘Grape’, ‘Tomato’, ‘Cucumber’, ‘Potato’, ‘Carrot’]

В природе существует специ­аль­ный метод для очистки списка — clear()

fruits = [‘Banana’, ‘Apple’, ‘Grape’]

vegetables = [‘Tomato’, ‘Cucumber’, ‘Potato’, ‘Carrot’]

fruits.clear()

vegetables.clear()

print(fruits)

print(vegetables)

>>> []

>>> []

Осталось совсем чуть-чуть всего лишь пара мето­дов, так что делаем последний рывок! Метод index() возв­ращает индекс эле­мента. Рабо­тает это так: вы пере­даете в качестве аргу­мента в index() значение элемента, а метод возв­ращает его индекс:

fruits = [‘Banana’, ‘Apple’, ‘Grape’]

print(fruits.index(‘Apple’))

print(fruits.index(‘Banana’))

print(fruits.index(‘Grape’))

>>> 1

>>> 0

>>> 2

Финишная прямая! Метод copy(), только не падайте, копирует список и возвра­щает его брата-близнеца. Вообще, копи­ро­вание списков – это тема доста­точно инте­ресная, давай­те рас­смотрим её по-подробнее.

Во-первых, если мы просто прис­воим уже сущест­вующий список новой пере­менной, то на первый взгляд всё выглядит неплохо:

fruits = [‘Banana’, ‘Apple’, ‘Grape’]

new_fruits = fruits

print(fruits)

print(new_fruits)

>>> [‘Banana’, ‘Apple’, ‘Grape’]

>>> [‘Banana’, ‘Apple’, ‘Grape’]

Но есть одно маленькое “НО”:

fruits = [‘Banana’, ‘Apple’, ‘Grape’]

new_fruits = fruits

fruits.pop()

print(fruits)

print(new_fruits)

# Внезапно, из списка new_fruits исчез последний элемент

>>> [‘Banana’, ‘Apple’]

>>> [‘Banana’, ‘Apple’]

При прямом присваивании спис­ков копи­рования не проис­ходит. Обе пере­менные начи­нают ссылаться на один и тот же список! То есть если мы изме­ним один из них, то изме­нится и другой. Что же тогда делать? Пользоваться методом copy(), конечно:

fruits = [‘Banana’, ‘Apple’, ‘Grape’]

new_fruits = fruits.copy()

fruits.pop()

print(fruits)

print(new_fruits)

>>> [‘Banana’, ‘Apple’]

>>> [‘Banana’, ‘Apple’, ‘Grape’]

Отлично! Но что если у нас список в списке? Скопируется ли внутренний список с помощью метода copy() — нет:

fruits = [‘Banana’, ‘Apple’, ‘Grape’, [‘Orange’,‘Peach’]]

new_fruits = fruits.copy()

fruits[-1].pop()

print(fruits) # 1

print(new_fruits) # 2

>>> [‘Banana’, ‘Apple’, ‘Grape’, [‘Orange’]] # 1

>>> [‘Banana’, ‘Apple’, ‘Grape’, [‘Orange’]] # 2

Решение задач

1. Создайте список из 10 четных чисел и выведите его с помощью цикла for

2. Создайте список из 5 элементов. Сделайте срез от второго индекса до четвертого

3. Создайте пустой список и добавьте в него 10 случайных чисел и выведите их. В данной задаче нужно использовать функцию randint.

from random import randint

n = randint(1, 10) # Случайное число от 1 до 10

4. Удалите все элементы из списка, созданного в задании 3

5. Создайте список из введенной пользователем строки и удалите из него символы ‘a’, ‘e’, ‘o’

6. Даны два списка, удалите все элементы первого списка из второго

a = [1, 3, 4, 5]

b = [4, 5, 6, 7]

# Вывод

>>> [6, 7]

7. Создайте список из случайных чисел и найдите наибольший элемент в нем.

8. Найдите наименьший элемент в списке из задания 7

9. Найдите сумму элементов списка из задания 7

10.Найдите среднее арифметическое элементов списка из задания 7

Сложные задачи

1. Создайте список из случайных чисел. Найдите номер его последнего локального максимума (локальный максимум — это элемент, который больше любого из своих соседей).

2. Создайте список из случайных чисел. Найдите максимальное количество его одинаковых элементов.

3. Создайте список из случайных чисел. Найдите второй максимум.

a = [1, 2, 3] # Первый максимум == 3, второй == 2

4. Создайте список из случайных чисел. Найдите количество различных элементов в нем.

List being an integral part of Python day-to-day programming has to be learned by all Python users and having a knowledge of its utility and operations is essential and always a plus. So this article discusses one such utility of finding the no. of elements in a list using Python.

Length of a List in Python

Python len() function is an inbuilt function in Python. It can be used to find the length of an object. 

Python3

li = [10, 20, 30]

n = len(li)

print("The length of list is: ", n)

Output: 

The length of list is: 3

Time Complexity: O(n), where n is the length of the list
Auxiliary Space: O(1)

Find the Length of a List in Python Naive Method

In this method, one just runs a loop and increases the counter till the last element of the list to know its count. This is the most basic strategy that can be possibly employed in the absence of other present techniques.

Python3

test_list = [1, 4, 5, 7, 8]

print("The list is : " + str(test_list))

counter = 0

for i in test_list:

    counter = counter + 1

print("Length of list using naive method is : " + str(counter))

Output: 

The list is : [1, 4, 5, 7, 8]
Length of list using naive method is : 5

Time Complexity: O(n)
Auxiliary Space: O(1)

Get the Length of a List in Python Using len()

The len() method offers the most used and easy way to find the python list length. This is the most conventional technique adopted by all programmers today.

Python3

a = []

a.append("Hello")

a.append("Geeks")

a.append("For")

a.append("Geeks")

print("The length of list is: ", len(a))

Output: 

The length of list is:  4

Time Complexity: O(n), where n is length of list
Auxiliary Space: O(1)

Find the Length of a List in Python Using length_hint()

This technique is a lesser-known technique for finding list length. This particular method is defined in the operator class and it can also tell the no. of elements present in the list. Here, we are finding length of list using len() and length_hint() 

Python3

from operator import length_hint

test_list = [1, 4, 5, 7, 8]

print("The list is : " + str(test_list))

list_len = len(test_list)

list_len_hint = length_hint(test_list)

print("Length of list using len() is : " + str(list_len))

print("Length of list using length_hint() is : " + str(list_len_hint))

Output : 

The list is : [1, 4, 5, 7, 8]
Length of list using len() is : 5
Length of list using length_hint() is : 5

Performance Analysis – Naive vs Python len() vs Python length_hint()

When choosing amongst alternatives it’s always necessary to have a valid reason why to choose one over another. This section does a time analysis of how much time it takes to execute all of them to offer a better choice to use.

Python3

from operator import length_hint

import time

test_list = [1, 4, 5, 7, 8]

print("The list is : " + str(test_list))

start_time_naive = time.time()

counter = 0

for i in test_list:

    counter = counter + 1

end_time_naive = str(time.time() - start_time_naive)

start_time_len = time.time()

list_len = len(test_list)

end_time_len = str(time.time() - start_time_len)

start_time_hint = time.time()

list_len_hint = length_hint(test_list)

end_time_hint = str(time.time() - start_time_hint)

print("Time taken using naive method is : " + end_time_naive)

print("Time taken using len() is : " + end_time_len)

print("Time taken using length_hint() is : " + end_time_hint)

Output:

The list is : [1, 4, 5, 7, 8]
Time taken using naive method is : 2.6226043701171875e-06
Time taken using len() is : 1.1920928955078125e-06
Time taken using length_hint() is : 1.430511474609375e-06

In the below images, it can be clearly seen that time taken is naive >> length_hint() > len(), but the time taken depends highly on the OS and several of its parameter. In two consecutive runs, you may get contrasting results, in fact sometimes naive takes the least time out of three. All the possible 6 permutations are possible.

  naive > len() > length_hint()

naive > len()=length_hint() 

naive > length_hint() >len() 

naive > length_hint()  > len()

Find the Length of a List in Python using sum()

Use iteration inside the sum and with each iteration adds one and at the end of the iteration, we get the total length of the list.

Python3

test_list = [1, 4, 5, 7, 8]

print("The list is : " + str(test_list))

list_len = sum(1 for i in test_list)

print("Length of list using len() is : " + str(list_len))

print("Length of list using length_hint() is : " + str(list_len))

Output:

The list is : [1, 4, 5, 7, 8]
Length of list using len() is : 5
Length of list using length_hint() is : 5

Find the Length of a List in Python using enumerate function

Python Enumerate() method adds a counter to an iterable and returns it in a form of an enumerating object. 

Python3

list1 = [1, 4, 5, 7, 8]

s = 0

for i, a in enumerate(list1):

    s += 1

print(s)

Find the Length of a List in Python using Collections

Alternatively, you can also use the sum() function along with the values() method of the Collections Counter object to get the length of the list.

Python3

from collections import Counter

test_list = [1, 4, 5, 7, 8]

list_len = sum(Counter(test_list).values())

print("Length of list using Counter() is:", list_len)

Output

Length of list using Counter() is: 5

Time complexity: O(n), where n is the length of the list. This is because the Counter() function has a time complexity of O(n) when applied to a list of length n, and the values() method and the sum() function both have a time complexity of O(n) when applied to a list of length n.

The space complexity: O(n), as the Counter() function, creates a dictionary with n key-value pairs, each representing an element and its count in the list, respectively. This dictionary takes up O(n) space.

Find the Length of a List in Python using a list comprehension

Initialize a list called test_list with some values then Initialize a variable called length to 0. Use a list comprehension to generate a sequence of ones for each element in the test_list. This will create a list of ones with the same length as the test_list. Now use the sum() function to sum all the ones in the list generated by the list comprehension. Assign the sum to the length variable. Print the length variable.

Python3

test_list = [1, 4, 5, 7, 8]

length = sum(1 for _ in test_list)

print("Length of list using list comprehension is:", length)

Output

Length of list using list comprehension is: 5

Time Complexity: The list comprehension creates a new list with a length equal to the length of the test_list. The sum() function then iterates over this list to compute the sum. Therefore, the time complexity of this algorithm is O(N), where N is the length of the test_list.

Auxiliary Space: The algorithm creates a new list of ones with a length equal to the length of the test_list using the list comprehension. Therefore, the auxiliary space complexity is also O(N), where N is the length of the test_list.

Find the Length of a List in Python using recursion

This function takes a list lst as input and recursively calls itself, passing in a slice of the list that excludes the first element, until the list is empty. The base case is when the list is empty, in which case the function returns 0. Otherwise, it adds 1 to the result of calling the function on the rest of the list.

Python3

def count_elements_recursion(lst):

    if not lst:

        return 0

    return 1 + count_elements_recursion(lst[1:])

lst = [1, 2, 3, 4, 5]

print("The length of the list is:", count_elements_recursion(lst))

Output

The length of the list is: 5

Time complexity: O(n) where n is the length of the list. This is because the function makes n recursive calls, each taking O(1) time, and there is also O(1) work done at each level outside of the recursive call.

Space complexity: O(n) where n is the length of the list. This is because the function creates n stack frames on the call stack due to the recursive calls.

How do I get the length of a list?

To find the number of elements in a list, use the builtin function len:

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

And now:

len(items)

returns 3.

Explanation

Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.

Lists and other similar builtin objects with a “size” in Python, in particular, have an attribute called ob_size, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.

But if you’re checking if list size is zero or not, don’t use len – instead, put the list in a boolean context – it is treated as False if empty, and True if non-empty.

From the docs

len(s)

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or
a collection (such as a dictionary, set, or frozen set).

len is implemented with __len__, from the data model docs:

object.__len__(self)

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t
define a __nonzero__() [in Python 2 or __bool__() in Python 3] method and whose __len__() method returns zero
is considered to be false in a Boolean context.

And we can also see that __len__ is a method of lists:

items.__len__()

returns 3.

Builtin types you can get the len (length) of

And in fact we see we can get this information for all of the described types:

>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list, 
                                            range, dict, set, frozenset))
True

Do not use len to test for an empty or nonempty list

To test for a specific length, of course, simply test for equality:

if len(items) == required_length:
    ...

But there’s a special case for testing for a zero length list or the inverse. In that case, do not test for equality.

Also, do not do:

if len(items): 
    ...

Instead, simply do:

if items:     # Then we have some items, not empty!
    ...

or

if not items: # Then we have an empty list!
    ...

I explain why here but in short, if items or if not items is more readable and performant than other alternatives.

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.

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.

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.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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

Use the len() function 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.

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.

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.

Добавить комментарий