Python как найти длину массива


An array is not a built-in data type in Python, but we can create arrays using third-party libraries. By length of an array, we mean the total number of elements or items in the given array. In order to calculate the length of an array, we can use various methods discussed below in this blog.

Table of contents

  1. Length of array
  2. Finding the length of an array using the len() function
  3. Using Numpy to find the length of an array in Python
  4. Closing thoughts

Length of array

In Python, an array is a collection of items stored at contiguous memory locations. It is a special variable, which can hold more than one value with the same data type at a time. We know array index starts from 0 instead of 1, therefore the length of an array is one more than the highest index value of the given array.

Finding the length of an array using the len() function

To find the length of an array in Python, we can use the len() function. It is a built-in Python method that takes an array as an argument and returns the number of elements in the array. The len() function returns the size of an array.

Syntax:

len (name_of_the_array)

Input:

arr = [0, 1, 2, a, 4]
print ("The given array is: ")
print (arr)

# Finding length of the given array
size = len(arr)
print ("The length of array is: ")
print (size) 

Output:

The given array is: 
[0, 1, 2, a, 4]
The length of array is: 
5

Using Numpy to find the length of an array in Python

Another method to find the length of an array is Numpy “size”. Numpy has a size attribute. The size is a built-in attribute that returns the size of the array.

Syntax:

name_of_the_array.size

Input:

import numpy as np

arr = np.array([0, 1, 2, a, 4])
print ("The given array is: ")
print (arr)


# Finding length of the given array
size = arr.size
print ("The length of array is: ")
print (size) 

Output:

The given array is: 
[0, 1, 2, a, 4]
The length of array is: 
5

Closing thoughts

Unlike other programming languages like JavaScript, PHP or C++, Python does not support “length()” or “size()” functions to find the length of an array. The len() function takes the array as a parameter and returns the size. One can read more about other Python concepts here.

В этой статье мы разберем, что такое массив в Python и как его использовать. Вы узнаете, как определять массивы и какие методы обычно используются для выполнения различных операций над ними.

Важно отметить, что в данной статье рассматриваются массивы, которые можно создать путем импорта модуля array. Массивы NumPy мы здесь рассматривать не будем.

Итак, мы разберем следующие темы:

  1. Введение в массивы
    • Основные различия между списками и массивами
    • Когда нужно использовать массивы
  2. Как использовать массив в Python
    • Определение массива
    • Поиск длины массива
    • Индексация массива
    • Поиск элементов в массиве
    • Использование циклов с массивами
    • Срезы массивов
  3. Методы массивов для выполнения различных операций
    • Изменение существующего значения
    • Добавление нового значения
    • Удаление значения
  4. Заключение

Что ж, давайте приступать!

Массив — это фундаментальная структура данных и важная часть большинства языков программирования. В Python массивы — это контейнеры, способные хранить более одного элемента одновременно.

В частности, они представляют собой упорядоченный набор элементов, каждое значение которого относится к одному и тому же типу данных. Это самое важное, что нужно помнить о массивах в Python. Они могут содержать последовательность нескольких элементов только одного типа.

В чем разница между списками и массивами в Python?

Списки — одна из наиболее распространенных структур данных в Python и основная часть языка.

Списки и массивы ведут себя сходным образом.

Как и массивы, списки представляют собой упорядоченную последовательность элементов.

Они также изменяемы и не имеют фиксированного размера, то есть могут увеличиваться и уменьшаться на протяжении всей жизни программы. Элементы можно добавлять и удалять, что делает списки очень гибкими в работе.

Однако списки и массивы — это не одно и то же.

В списках могут храниться элементы различных типов данных. Это означает, что список может одновременно содержать целые числа, числа с плавающей запятой, строки или любой другой тип данных Python. С массивами это не сработает.

Как уже упоминалось, массивы хранят элементы только какого-то одного типа данных. Это важно помнить! Есть массивы целых чисел, массивы чисел с плавающей запятой и т.д.

[python_ad_block]

Когда следует использовать массивы в Python

Списки встроены по умолчанию в язык программирования Python, а массивы — нет. Поэтому, если вы хотите использовать массивы, их сперва нужно импортировать через модуль array.

Массивы модуля array представляют собой тонкую обертку массивов в C. Они полезны, когда вам нужно работать с однородными данными.

Они также более компактны и занимают меньше памяти и места, что делает их более эффективными по сравнению со списками.

Если вы хотите выполнять математические вычисления, лучше воспользоваться массивами NumPy, импортировав модуль NumPy.

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

Как использовать массивы в Python

Чтобы создавать массивы в Python, вам сначала нужно импортировать модуль array, который содержит все необходимые для работы функции.

Импортировать модуль массива можно тремя способами:

1. Использовать import array в верхней части файла. Это позволит нам подключить модуль array. После чего мы сможем создать массив, используя array.array().

import array

# Создание массива
array.array()

2. Чтобы не вводить постоянно array.array(), можно прописать import array as arr в верхней части файла вместо просто import array. После чего для создания массива нужно будет набрать arr.array(). Arr действует как псевдоним, после которого сразу следует конструктор для создания массива.

import array as arr

# Создание массива
arr.array()

3. Наконец, вы также можете использовать from array import *, где с помощью * импортируются все доступные функции данного модуля. В таком случае, чтобы создать массив, нужно написать просто array().

from array import *

# Создание массива
array()

Как определить массив в Python

После того, как вы импортировали модуль array, вы можете перейти к непосредственному созданию массива Python.

Общий синтаксис создания массива выглядит следующим образом:

variable_name = array(typecode,[elements])

Давайте разберем синтаксис подробнее:

  • variable_name будет именем массива
  • typecode указывает, какие элементы будут храниться в массиве. Это может быть массив целых чисел, массив чисел с плавающей запятой или массив любого другого типа данных в Python. Но помните, что все элементы должны быть одного типа данных.
  • Внутри квадратных скобок вы указываете элементы, которые будут храниться в массиве, при этом каждый элемент отделяется запятой. Вы также можете создать пустой массив, просто написав variable_name = array(typecode) без каких-либо элементов.

Ниже приведена таблица кодов для различных типов данных.

TYPECODE Тип в C Тип в Python Размер
‘b’ signed char int 1
‘B’ unsigned char int 1
‘u’ wchar_t Unicode character 2
‘h’ signed short int 2
‘H’ unsigned short int 2
‘i’ signed int int 2
‘I’ unsigned int int 2
‘l’ signed long int 4
‘L’ unsigned long int 4
‘q’ signed long long int 8
‘Q’ unsigned long long int 8
‘f’ float float 4
‘d’ double float 8

Создание массива на практике

Вот пример того, как можно определить массив в Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Давайте разберем, что мы только что сделали.

Сначала мы подключили модуль array, в данном случае с помощью import array as arr.

Затем мы создали массив чисел.

Мы использовали arr.array(), так как arr это наш псевдоним для модуля.

Внутри конструктора array() мы сначала указали i для целых чисел. Это означает, что массив может включать как положительные, так и отрицательные значения. Если бы мы, например, указали H, это бы означало, что отрицательные значения не допускаются.

Наконец, мы перечислили значения, которые будут храниться в массиве, в квадратных скобках.

Имейте в виду, что если вы попытаетесь включить значения, тип которых не соответствует коду i, то есть не целочисленные значения, вы получите сообщение об ошибке:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

В этом примере мы попытались включить в массив число с плавающей запятой. И получили ошибку, потому что это целочисленный массив.

Другой способ создания массива:

from array import *

# Массив чисел с плавающей запятой
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

В этом примере модуль массива был импортирован через from array import *. Затем был создан массив чисел с типом данных float. Это означает, что он содержит только числа с плавающей запятой, которым соответствует код d.

Как найти длину массива в Python

Чтобы узнать точное количество элементов, содержащихся в массиве, можно использовать встроенный метод len().

Он вернет вам целое число, равное общему количеству элементов в указанном вами массиве.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

В этом примере массив содержал три элемента — 10, 20, 30. Поэтому длина массива равна 3.

Индексация массива и доступ к отдельным элементам

Каждый элемент массива имеет определенный адрес. Доступ к отдельным элементам осуществляется путем ссылки на их порядковый номер.

Индексация в Python, как и во всех языках программирования, и вычислениях в целом начинается с 0, а не с 1. Об этом важно помнить.

Чтобы получить доступ к элементу, вы сначала пишете имя массива, за которым следуют квадратные скобки. Внутри квадратных скобок вы указываете индекс нужного элемента.

Общий синтаксис будет выглядеть так:

array_name[index_value_of_item]

Вот так можно получить доступ к каждому отдельному элементу в массиве:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # Получение 1-го элемента
print(numbers[1]) # Получение 2-го элемента
print(numbers[2]) # Получение 3-го элемента

#output

#10
#20
#30

Помните, что значение индекса последнего элемента массива всегда на единицу меньше, чем длина массива. Если n — длина массива, то значением индекса последнего элемента будет n-1.

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

При отрицательной индексации последний элемент будет иметь индекс -1, предпоследний элемент — -2 и так далее.

К примеру, получить каждый элемент массива можно следующим образом:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) # Получение последнего элемента
print(numbers[-2]) # Получение предпоследнего элемента
print(numbers[-3]) # Получение первого элемента
 
#output

#30
#20
#10

Как искать элемент в массиве в Python

Вы можете узнать порядковый номер элемента с помощью метода index().

В качестве аргумента метода вы передаете значение искомого элемента, и вам возвращается его индекс.

import array as arr 

numbers = arr.array('i',[10,20,30])

# Поиск индекса элемента со значением 10
print(numbers.index(10))

#output

#0

Если имеется более одного элемента с указанным значением, будет возвращен индекс элемента, который встречается первым. К примеру, это может выглядеть так:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

# Поиск индекса элемента со значением 10
# Возвращается индекс первого из двух элементов со значением 10
print(numbers.index(10))

#output

#0

Как перебрать массив в Python с помощью цикла

Мы рассмотрели, как получить доступ к каждому отдельному элементу массива и распечатать элементы по отдельности.

Вы также видели, как распечатать массив с помощью метода print(). Этот метод дает следующий результат:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

Но что делать, если вы хотите вывести значения одно за другим?

Здесь на помощь приходит цикл. Вы можете идти по массиву и распечатывать значения одно за другим с каждой новой итерацией цикла. Подробнее о циклах в Python можно почитать в статье «Pythonic циклы».

К примеру, для решения нашей задачи вы можете использовать простой цикл for:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

Вы также можете использовать функцию range() и передать метод len() в качестве ее параметра. Это даст тот же результат:

import array as arr  

values = arr.array('i',[10,20,30])

# Распечатка всех значений массива по отдельности
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

Как использовать срезы с массивами в Python

Чтобы получить доступ к определенному диапазону значений внутри массива, используйте оператор среза (двоеточие :).

Если, используя срез, вы укажете только одно значение, отсчет по умолчанию начнется с 0. Код получает первый элемент (с индексом 0) и идет до элемента с указанным вами индексом, но не захватывает его.

import array as arr 

# Исходный массив
numbers = arr.array('i',[10,20,30])

# Получение только значений 10 и 20
print(numbers[:2])  # С первой по вторую позицию (индексы 0 и 1)

#output

#array('i', [10, 20])

Когда вы передаете два числа в качестве аргументов, вы указываете диапазон индексов. В этом случае отсчет начинается с первого указанного вами индекса и идет до второго, не включая его:

import array as arr 

# Исходный массив
numbers = arr.array('i',[10,20,30])


# Получение только значений 20 и 30
print(numbers[1:3]) # Со второй по третью позицию

#output

#array('i', [20, 30])

Методы выполнения операций с массивами в Python

Массивы изменчивы, это означает, что мы можем менять их элементы самым разным образом. Можно изменить значение элементов, добавить новые или удалить те, которые вам больше не нужны в вашей программе.

Давайте рассмотрим несколько методов, наиболее часто используемых для выполнения операций с массивами.

Изменение значения элемента в массиве

Вы можете изменить значение определенного элемента, указав его позицию (индекс) и присвоив ему новое значение. Сделать это можно так:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

# Изменение первого элемента
# Меняется значение с 10 на 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

Добавление нового значения в массив

Чтобы добавить одно значение в конец массива, используйте метод append():

import array as arr 

# Исходный массив
numbers = arr.array('i',[10,20,30])

# В конец  numbers добавляется целое число 40 
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Имейте в виду, что новый элемент, который вы добавляете, должен иметь тот же тип данных, что и остальные элементы в массиве.

Посмотрите, что произойдет, если мы пытаемся добавить число с плавающей запятой в массив целых чисел:

import array as arr 

# Исходный массив
numbers = arr.array('i',[10,20,30])

# В конец numbers добавляется число с плавающей запятой 40.0
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

Но что, если вы хотите добавить более одного значения в конец массива?

Тогда используйте метод extend(), который принимает итерируемый объект (например, список элементов) в качестве аргумента. Опять же, убедитесь, что все новые элементы имеют один и тот же тип данных.

import array as arr 

# Исходный массив
numbers = arr.array('i',[10,20,30])

# Добавление целых чисел 40,50,60 в конец numbers
# Числа берутся в квадратные скобки

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

А что, если вы  хотите добавить элемент не в конец массива? В таком случае используйте метод insert(): он позволяет добавить элемент на определенную позицию.

Функция insert() принимает два аргумента: индекс позиции, на которую будет вставлен новый элемент, и значение нового элемента.

import array as arr 

# Исходный массив
numbers = arr.array('i',[10,20,30])

# Добавление целого числа 40 на первую позицию
# Помните, что индексация начинается с  0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

Удаление значения из массива

Чтобы удалить элемент из массива, используйте метод remove() и укажите значение элемента в качестве аргумента.

import array as arr 

# Исходный массив
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

С помощью remove() будет удален только первый экземпляр значения, которое вы передаете в качестве аргумента.

Посмотрите, что происходит, когда имеется несколько элементов с одинаковым значением:

import array as arr 

# Исходный массив
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Удаляется только первое вхождение числа 10.

Вы также можете использовать метод pop() и указать позицию удаляемого элемента:

import array as arr 

# Исходный массив
numbers = arr.array('i',[10,20,30,10,20])

# Удаление первого вхождения 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Заключение

Вот и все — теперь вы знаете, что такое массив в Python, как его создать с помощью модуля array и какие есть методы для работы с ним. Надеемся, это руководство было вам полезно.

Спасибо за чтение и успехов в написании кода!

Перевод статьи «Python Array Tutorial – Define, Index, Methods».

Length of Array in Python

Overview

We have learned that arrays are a collection of objects, and these collections can have any number of objects: zero, one, ten, and so on. The number of objects in the array is called its length. We need to know the length of an array to perform various operations like iterating over the array, checking whether an element belongs to the array and reading/updating elements in the array.

Scope

  • In this article, we shall see how the length of an array is calculated in Python using default libraries as well as NumPy library.
  • We will not discuss how these library methods internally work to compute the length of an array in Python programming.

Introduction

Let us take an array as follows:


How many elements are in the array? The answer is 5. Hence the length of the array is also 5.

If we were to give indexes to each element in the array as follows:

introduction link

Essentially, the length of an array is the highest index position + 1.

Array Length in Python using the len() method

Python has a len() method to find out the length of an array. The syntax is as follows:


Example

arr = [1,6,3,7,1]
print("Elements in the array: ", arr)
print("Length of the array: ", len(arr))

Output

Elements in the array: [1,6,3,7,1]
Length of the array: 5

Finding the Length of a Python NumPy Array

Numpy is a library compatible with Python for operating complex mathematical operations on multi-dimensional arrays. We use numpy for mathematical operations on arrays. Here is how we can find the length of an array in Python using numpy:

Example

import numpy as np

arr = np.array([1,6,3,7,1])
print("Elements in the array: ", arr)
print("Length of the array: ", len(arr))

Output

Elements in the array:  [1 6 3 7 1]
Length of the array:  5

Conclusion

  • Length of an array is the number of elements present in the array.
  • In python, the length of an array is the highest index of an array + 1.
  • We can use Python’s len() function to find the length of an array.
  • For a Numpy array also, we can use the len() function to find the array’s length in Python.

Python len() method is used to find the length of an array. As we all know, python does not support or provide us with the array data structure in a direct way. Instead, python serves with three different variations of using an array data structure.

In this tutorial, we will learn about the fundamentals of the different array variants that can use to create an array in python and then we will discuss the use of the len() method to obtain the length of an array in each variant.

Finding the length of an Array using the len() Method

We have three methods to create an array in Python, which we will use to demonstrate the use of the len() method.

  • Python List
  • Python Array Module
  • NumPy Module

To demonstrate the len() method, we’ll use all of these types of arrays, but before that let’s take a look at the syntax of len() method.

len() Method in Python

Python len() method enables us to find the total number of elements in an array. It returns the count of the elements in an array.

Syntax:

Here, the array can be any type of array for which we want to find the length.

Finding the Length of a Python List using len() Method

The Python len() method can be used to fetch and display the number of elements contained in the list.

Example:

In the below example, we have created a list of heterogeneous elements. Further, we have used len() method to display the length of the list.

lst = [1,2,3,4,'Python']
print("List elements: ",lst)
print("Length of the list:",len(lst))

Output:

List elements:  [1, 2, 3, 4, 'Python']
Length of the list: 5

Finding the Length of a Python Array using len() Method

Python Array module helps us create an array and manipulate the same using various functions of the module. The len() method can also be used to calculate the length of an array created using the Array module.

Example:

import array as A 
arr = A.array('i',[1,2,3,4,5])
print("Array elements: ",arr)
print("Length of array: ",len(arr))

Output:

Array elements:  array('i', [1, 2, 3, 4, 5])
Length of array: 5

Finding the Length of a Python NumPy Array using len() Method

As we all know, we can create an array using NumPy module and use it for any mathematical purpose. The len() method helps us find out the number of data values present in a NumPy array.

Example:

import numpy as np
arr = np.arange(5)
len_arr = len(arr)
print("Array elements: ",arr)
print("Length of NumPy array: ",len_arr)

Output:

Array elements:  [0 1 2 3 4]
Length of NumPy array: 5

Conclusion

In this tutorial, we learned to use the len() method to find the length of different arrays in Python. We have given you many examples so that you can learn them well. Hope you find this tutorial useful.

Reference

https://stackoverflow.com/questions/518021/is-arr-len-the-preferred-way-to-get-the-length-of-an-array-in-python

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.

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