Массив как пишется питон

Python_Deep_14.3_site-5020-9131b4.png

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

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

Пустой список:


Массив строк в Python:

Prime = ['string1', 'string2', 'string3'] 
Prime[1] = 'string2'; //true 

Чтобы возвратить число элементов внутри списка, используют функцию len():


Когда нужно перечислить элементы массива, применяют цикл for. В «Питоне» этот цикл перебирает элементы, а не индексы, как в Pascal:


Идём дальше. Создать и добавить цикл в Python можно с помощью генератора заполнения списков. Записывается он в следующем виде:
[значение массива for имя переменной in число элементов];

Если говорить про создание не одномерного, а двумерного массива, то он в Python создаётся путём использования вложенных генераторов, и выглядит это так:

[[0 for j in range(m)] for i in range(n)]

matrix_python-20219-889f47.jpg

Как создаются матрицы в Python?

Добавление и модификация массивов или матриц (matrix) в Python осуществляется с помощью библиотеки NumPy. Вы можете создать таким образом и одномерный, и двумерный, и многомерный массив. Библиотека обладает широким набором пакетов, которые необходимы, чтобы успешно решать различные математические задачи. Она не только поддерживает создание двумерных и многомерных массивов, но обеспечивает работу однородных многомерных матриц.

Чтобы получить доступ и начать использовать функции данного пакета, его импортируют:


Функция array() — один из самых простых способов, позволяющих динамически задать одно- и двумерный массив в Python. Она создаёт объект типа ndarray:

array = np.array(/* множество элементов */)

Для проверки используется функция array.type() — принимает в качестве аргумента имя массива, который был создан.

Если хотите сделать переопределение типа массива, используйте на стадии создания dtype=np.complex:

array2 = np.array([ /*элементы*/, dtype=np.complex)

Когда стоит задача задать одномерный или двумерный массив определённой длины в Python, и его значения на данном этапе неизвестны, происходит его заполнение нулями функцией zeros(). Кроме того, можно получить матрицу из единиц через функцию ones(). При этом в качестве аргументов принимают число элементов и число вложенных массивов внутри:


К примеру, так в Python происходит задание двух массивов внутри, которые по длине имеют два элемента:

array([ 
[[0, 0]] 
[[0, 0]]] 
) 

Если хотите вывести одно- либо двумерный массив на экран, вам поможет функция print(). Учтите, что если матрица слишком велика для печати, NumPy скроет центральную часть и выведет лишь крайние значения. Дабы увидеть массив полностью, используется функция set_printoptions(). При этом по умолчанию выводятся не все элементы, а происходит вывод только первой тысячи. И это значение массива указывается в качестве аргумента с ключевым словом threshold.

Базовые операции в NumPy

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

array1 = np.array([[1, 2, 3], [1, 2, 3]])
array2 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])

Если выполнить array1 + array2, компилятор скажет об ошибке, а всё потому, что размер первого matrix равен двум, а второго трём.

array1 = np.array([1, 2, 5, 7]) 
array2 = arange([1, 5, 1]) 

В данном случае array1 + array2 вернёт нам массив со следующими элементами: 2, 4, 8, 11. Здесь не возникнет ошибки, т. к. матрицы имеют одинаковые размеры. Причём вместо ручного сложения часто применяют функцию, входящую в класс ndarray sum():

np.array(array1 + array1) == array1 + array2

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

Форма матрицы в Python

Lenght matrix (длина матрицы) в Python определяет форму. Длину матрицы проверяют методом shape().

Массив с 2-мя либо 3-мя элементами будет иметь форму (2, 2, 3). И это состояние изменится, когда в shape() будут указаны аргументы: первый — число подмассивов, второй — размерность каждого подмассива.

Те же задачи и ту же операцию выполнит reshape(). Здесь lenght и другие параметры matrix определяются числом столбцов и строк.

Есть методы и для манипуляции формой. Допустим, при манипуляциях с двумерными или многомерными массивами можно сделать одномерный путём выстраивания внутренних значений последовательно по возрастанию. А чтобы поменять в матрице строки и столбцы местами, применяют transpose().

Операции со срезами matrix в Python

Часто мы работаем не с целым массивом, а с его компонентами. Эти операции выполняются с помощью метода слайс (срез). Он пришел на замену циклу for, при котором каждый элемент подвергался перебору. Метод позволяет получать копии matrix, причём манипуляции выполняются в виде [start:stop:step]. В данном случае start — индекс элемента, с которого берётся отсчёт, stop — последний элемент, step — размер шага или число пропускаемых значений элемента при каждой итерации. Изначально start равен нулю, stop — индексу последнего элемента, step — единице. Если выполнить операции без аргументов, копирование и добавление списка произойдёт полностью.

Допустим, имеем целочисленный массив otus = [1, 2, 3, 4]. Для копирования и вывода используем otus[:]. В итоге произойдёт вывод последовательности [1, 2, 3, 4]. Но если аргументом станет отрицательное значение, допустим, -2, произойдёт вывод уже других данных:


Возможны и другие операции. Например, если добавить ещё одно двоеточие, будет указан шаг копируемых элементов. Таким образом, otus[::2] позволит вывести матрицу [1, 3].

Если ввести отрицательное значение, к примеру, [::-2] отсчёт начнётся с конца, и в результате произойдёт вывод [3, 1]. Остаётся добавить, что метод среза позволяет гибко работать с матрицами и вложенными списками в Python.

Хотите узнать гораздо больше? Записывайтесь на курс «Разработчик Python»!

В этой статье мы разберем, что такое массив в 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».

Python Array Tutorial – Define, Index, Methods

In this article, you’ll learn how to use Python arrays. You’ll see how to define them and the different methods commonly used for performing operations on them.

The article covers arrays that you create by importing the array module. We won’t cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let’s get started!

What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays — the fact that they can only hold a sequence of multiple items that are of the same type.

What’s the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren’t. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you’ll first have to import the array module which contains all the necessary functions.

There are three ways you can import the array module:

  1. By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  1. Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  1. Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you’ve imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let’s break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

Typecode C type Python Type Size
‘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

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

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


print(numbers)

#output

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

Let’s break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

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

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

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

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

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


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item’s index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

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

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

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

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element’s index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element’s index number is returned.

import array as arr 

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

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


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

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You’ve seen how to access each individual element in an array and print it out on its own.

You’ve also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

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

print(numbers)

#output

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

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

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

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

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

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

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.


import array as arr 

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

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

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

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

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


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

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

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don’t want in your program anymore.

Let’s see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

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

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

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

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

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

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

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

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

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

#add the float 40.0 to the end of numbers
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

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

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

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

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

print(numbers)

#output

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

And what if you don’t want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

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

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

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

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

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

numbers.remove(10)

print(numbers)

#output

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

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:


import array as arr 

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

numbers.remove(10)

print(numbers)

#output

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

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

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

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

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

Conclusion

And there you have it — you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

To learn more about Python, check out freeCodeCamp’s Scientific Computing with Python Certification.

You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

References: Python documentation



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

Table of Contents

In programming, an array is a homogenous (belonging to the same data type) collection of elements. Unlike languages like C++, Java, and JavaScript, arrays aren’t among the built-in Python data structures.

Although Python doesn’t have built-in support for arrays, that doesn’t stop programmers from implementing them.

What are Python Arrays

As a replacement to arrays, Python has lists. Nonetheless, Python supports arrays of numeric values using the array module.

When creating arrays using the array module in Python, remember that all elements of the array must be of the same type. If this is not the case then an error will be produced. For instance,

a = [1, 22, 240] is valid

but

a = [1, 22, 240, “Akhil”] is not valid and will thus, yield an error

Length of an Array

The len() method returns the length of an array i.e. the number of elements in an array. 

Example
Return the number of elements in the phones array:

x = len(phones)

Recommend Python Course

Complete Python Bootcamp From Zero to Hero in Python

Creating Arrays/ How to Declare Arrays in Python

Before declaring arrays, it is required to import the array module. For instance, take a look at the following code snippet:

import array as ar1
a = ar1.array(‘d’, [1.2, 2.2, 2.4, 4.6])
print (a)

Output:

array(‘d’, [1.2, 2.2, 2.4, 4.6])

We’ve created an array of float type after importing the array module. The letter ‘d’ is a type code that determines the type of array during creation. Following are some of the most important array type codes in Python:

  • ‘b’ – signed char
  • ‘B’ – unsigned char
  • ‘d’ – double
  • ‘f’ – float
  • ‘h’ – signed short
  • ‘H’ – unsigned short
  • ‘i’ – signed int
  • ‘I’ – unsigned int
  • ‘l’ – signed long
  • ‘L’ – unsigned long

Accessing Array Elements in Python

Indices are used for accessing elements of an array in Python. Like lists, the index starts from 0. For example:

import array as ar1
a = ar1.array (‘i’, [22, 24, 46, 53])
print(“The first element of the array:”, a[0])
print(“The second element of the array:”, a[1])
print(“The last element of the array:”, a[2])

Output:

The first element of the array: 22

The second element of the array: 24

The last element of the array: 53

Slicing Arrays in Python

By using the slicing operator (:), it is possible to access a range of elements present in an array in Python programming language. Following code snippet demonstrates using the slicing operator with an array in Python:

import array as ar1
number_list = [2, 4, 22, 25, 24, 52, 46, 5]
number_array = ar1.array('i', number_list)
print(numbers_array[2:5]) # third to fifth
print(numbers_array[:-5]) # beginning to forth
print(numbers_array[5:]) # sixth to end
print(numbers_array[:]) # beginning to end

Output:

array(‘i’, [22, 25, 24])

array(‘i’, [2, 4, 22, 25])

array(‘i’, [46, 5])

array(‘i’, [2, 4, 22, 25, 24, 52, 46, 5])

Adding or Changing Elements

Arrays are mutable. Hence, their elements can be changed in a similar way as lists. Consider the following code sample:

import array as ar1
numbers = ar1.array('i', [1, 2, 3, 4, 6, 10])
numbers[0] = 0 # replacing the first element 1 with 0
print(numbers)
numbers[2:5] = arr.array('i', [4, 6, 8]) # changing third, fourth, and fifth elements
print(numbers)

Output:

array(‘i’, [0, 2, 3, 4, 6, 10])

array(‘i’, [0, 2, 4, 6, 8, 10])

The append() method is used for adding one element to an array while the extend() method allows adding multiple elements. These new elements are added to the end of the array. Observe the following code snippet:

import array as ar1
numbers = ar1.array('i', [1, 2, 3])
numbers.append(4) # adds 4 to the array at the last position
print(numbers)
numbers.extend([5, 6, 7]) # appends iterable to the end of the array
print(numbers)

Output:

array(‘i’, [1, 2, 3, 4])

array(‘i’, [1, 2, 3, 4, 5, 6, 7])

The concatenation operator (+) is used for concatenating two arrays in Python programming language. For example:

import array as ar1
odd = ar1.array('i', [11, 33, 55])
even = ar1.array('i', [22, 44, 66])
numbers = ar1.array('i') # creates an empty array of integer
numbers = odd + even
print(numbers)

Output:

array(‘i’, [11, 22, 33, 44, 55, 66])

Deleting Elements from an Array

The del statement can be used for removing one or more elements from an array in Python. For instance:

import array as ar1
number = ar1.array('i', [11, 22, 33, 33, 44])
del number[2] # removes the third element
print(number)
del number # deletes the entire array
print(number)

Output:

array(‘i’, [11, 22, 33, 44])

Error: array is not defined

While the remove() method can be used for removing a specific element from the array, the pop() method allows for removing a specific element and display it. Use of both these methods are illustrated in the following code snippet:

import array as ar1
numbers = ar1.array('i', [10, 11, 12, 12, 13])
numbers.remove(12)
print(numbers)
print(numbers.pop(2))
print(numbers)

Output:

array(‘i’, [10, 11, 12, 13])

12

array(‘i’, [10, 11, 13])

Searching an Element in Array

Based on the index or value of the element, it is possible to search for the same in an array. The index() method is used for searching an element in an array based on its value. The method returns the index of the element being searched. For instance:

import array as ar1
numbers = ar1.array('i', [10,20,30,40,50])
print (array1.index(40)) # returns the index of the element 40

Output:

3

In case there is no such element that is being searched in an array, the program will give out an error.

Array Methods

These are the various inbuilt methods in Python for using with arrays:

  • append() – Adds an element at the end of the array list
  • clear() – Eliminates all elements from the array list
  • copy() – Returns a copy of the array list
  • count() – Returns the elements along with their total number
  • extend() – Add the elements of an array list to the end of the current list
  • index() – Returns the index of the first element in an array list with the specified value
  • insert() – Adds an element to the specified position in the array list
  • pop() – Removes an element from the specified position
  • remove() – Eliminates the first element with the specified value
  • reverse() – Reverses the order of an array list
  • sort() – Sorts the array list

Conclusion

Although knowing how to deal with arrays isn’t a mandatory part of learning Python, able to do so is surely an added advantage. This is especially true when dealing with churning out arrays and matrices. Nonetheless, lists in Python are way much more flexible than arrays.

Unlike arrays, lists are able to store elements belonging to different data types and are faster. Typically, the array module is required for interfacing with C code. It is typically advised to avoid using arrays in Python. However, that doesn’t mean that you can’t learn them.

Check out these best Python books to help you through and make your Python learning better and more insightful.

People are also reading:

  • Best Python Courses
  • Best Python Certifications
  • Top Python Projects
  • Best Python Compilers
  • Best Python Interpreters
  • Best way to learn python
  • Python Programming languages
  • How to Run a Python Script?
  • What is PyCharm?
  • Python for Data Science
  • Top Python Libraries

Table of Contents

In programming, an array is a homogenous (belonging to the same data type) collection of elements. Unlike languages like C++, Java, and JavaScript, arrays aren’t among the built-in Python data structures.

Although Python doesn’t have built-in support for arrays, that doesn’t stop programmers from implementing them.

What are Python Arrays

As a replacement to arrays, Python has lists. Nonetheless, Python supports arrays of numeric values using the array module.

When creating arrays using the array module in Python, remember that all elements of the array must be of the same type. If this is not the case then an error will be produced. For instance,

a = [1, 22, 240] is valid

but

a = [1, 22, 240, “Akhil”] is not valid and will thus, yield an error

Length of an Array

The len() method returns the length of an array i.e. the number of elements in an array. 

Example
Return the number of elements in the phones array:

x = len(phones)

Recommend Python Course

Complete Python Bootcamp From Zero to Hero in Python

Creating Arrays/ How to Declare Arrays in Python

Before declaring arrays, it is required to import the array module. For instance, take a look at the following code snippet:

import array as ar1
a = ar1.array(‘d’, [1.2, 2.2, 2.4, 4.6])
print (a)

Output:

array(‘d’, [1.2, 2.2, 2.4, 4.6])

We’ve created an array of float type after importing the array module. The letter ‘d’ is a type code that determines the type of array during creation. Following are some of the most important array type codes in Python:

  • ‘b’ – signed char
  • ‘B’ – unsigned char
  • ‘d’ – double
  • ‘f’ – float
  • ‘h’ – signed short
  • ‘H’ – unsigned short
  • ‘i’ – signed int
  • ‘I’ – unsigned int
  • ‘l’ – signed long
  • ‘L’ – unsigned long

Accessing Array Elements in Python

Indices are used for accessing elements of an array in Python. Like lists, the index starts from 0. For example:

import array as ar1
a = ar1.array (‘i’, [22, 24, 46, 53])
print(“The first element of the array:”, a[0])
print(“The second element of the array:”, a[1])
print(“The last element of the array:”, a[2])

Output:

The first element of the array: 22

The second element of the array: 24

The last element of the array: 53

Slicing Arrays in Python

By using the slicing operator (:), it is possible to access a range of elements present in an array in Python programming language. Following code snippet demonstrates using the slicing operator with an array in Python:

import array as ar1
number_list = [2, 4, 22, 25, 24, 52, 46, 5]
number_array = ar1.array('i', number_list)
print(numbers_array[2:5]) # third to fifth
print(numbers_array[:-5]) # beginning to forth
print(numbers_array[5:]) # sixth to end
print(numbers_array[:]) # beginning to end

Output:

array(‘i’, [22, 25, 24])

array(‘i’, [2, 4, 22, 25])

array(‘i’, [46, 5])

array(‘i’, [2, 4, 22, 25, 24, 52, 46, 5])

Adding or Changing Elements

Arrays are mutable. Hence, their elements can be changed in a similar way as lists. Consider the following code sample:

import array as ar1
numbers = ar1.array('i', [1, 2, 3, 4, 6, 10])
numbers[0] = 0 # replacing the first element 1 with 0
print(numbers)
numbers[2:5] = arr.array('i', [4, 6, 8]) # changing third, fourth, and fifth elements
print(numbers)

Output:

array(‘i’, [0, 2, 3, 4, 6, 10])

array(‘i’, [0, 2, 4, 6, 8, 10])

The append() method is used for adding one element to an array while the extend() method allows adding multiple elements. These new elements are added to the end of the array. Observe the following code snippet:

import array as ar1
numbers = ar1.array('i', [1, 2, 3])
numbers.append(4) # adds 4 to the array at the last position
print(numbers)
numbers.extend([5, 6, 7]) # appends iterable to the end of the array
print(numbers)

Output:

array(‘i’, [1, 2, 3, 4])

array(‘i’, [1, 2, 3, 4, 5, 6, 7])

The concatenation operator (+) is used for concatenating two arrays in Python programming language. For example:

import array as ar1
odd = ar1.array('i', [11, 33, 55])
even = ar1.array('i', [22, 44, 66])
numbers = ar1.array('i') # creates an empty array of integer
numbers = odd + even
print(numbers)

Output:

array(‘i’, [11, 22, 33, 44, 55, 66])

Deleting Elements from an Array

The del statement can be used for removing one or more elements from an array in Python. For instance:

import array as ar1
number = ar1.array('i', [11, 22, 33, 33, 44])
del number[2] # removes the third element
print(number)
del number # deletes the entire array
print(number)

Output:

array(‘i’, [11, 22, 33, 44])

Error: array is not defined

While the remove() method can be used for removing a specific element from the array, the pop() method allows for removing a specific element and display it. Use of both these methods are illustrated in the following code snippet:

import array as ar1
numbers = ar1.array('i', [10, 11, 12, 12, 13])
numbers.remove(12)
print(numbers)
print(numbers.pop(2))
print(numbers)

Output:

array(‘i’, [10, 11, 12, 13])

12

array(‘i’, [10, 11, 13])

Searching an Element in Array

Based on the index or value of the element, it is possible to search for the same in an array. The index() method is used for searching an element in an array based on its value. The method returns the index of the element being searched. For instance:

import array as ar1
numbers = ar1.array('i', [10,20,30,40,50])
print (array1.index(40)) # returns the index of the element 40

Output:

3

In case there is no such element that is being searched in an array, the program will give out an error.

Array Methods

These are the various inbuilt methods in Python for using with arrays:

  • append() – Adds an element at the end of the array list
  • clear() – Eliminates all elements from the array list
  • copy() – Returns a copy of the array list
  • count() – Returns the elements along with their total number
  • extend() – Add the elements of an array list to the end of the current list
  • index() – Returns the index of the first element in an array list with the specified value
  • insert() – Adds an element to the specified position in the array list
  • pop() – Removes an element from the specified position
  • remove() – Eliminates the first element with the specified value
  • reverse() – Reverses the order of an array list
  • sort() – Sorts the array list

Conclusion

Although knowing how to deal with arrays isn’t a mandatory part of learning Python, able to do so is surely an added advantage. This is especially true when dealing with churning out arrays and matrices. Nonetheless, lists in Python are way much more flexible than arrays.

Unlike arrays, lists are able to store elements belonging to different data types and are faster. Typically, the array module is required for interfacing with C code. It is typically advised to avoid using arrays in Python. However, that doesn’t mean that you can’t learn them.

Check out these best Python books to help you through and make your Python learning better and more insightful.

People are also reading:

  • Best Python Courses
  • Best Python Certifications
  • Top Python Projects
  • Best Python Compilers
  • Best Python Interpreters
  • Best way to learn python
  • Python Programming languages
  • How to Run a Python Script?
  • What is PyCharm?
  • Python for Data Science
  • Top Python Libraries

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

Списки и массивы

Главное различие между ними заключается в том, что списки могут хранить разнородные данные, а массивы — только данные одного типа. Например, только строки или только числа, причем отдельно целые и отдельно с плавающей запятой. Поэтому вот такой список в Python:

list = ['element1', 'element2', 'element3']

одновременно выполняет и функции массива. Как видим, элементы списка располагаются внутри квадратных скобок и перечисляются через запятую. Здесь мы взяли для примера строки. Рассмотрим еще один пример:

>>> different = ['55', 'string', '32.5', ['list_in_list', '55', 'string', '32.5']]
>>> print(different)
['55', 'string', '32.5', ['list_in_list', '55', 'string', '32.5']]

Это тоже список с функциями массива, поскольку все элементы здесь оформлены в виде строк. А теперь давайте напишем следующее:

>>> different2 = [55, 'string', 32.5, ['list_in_list', '55', 'string', '32*8']]
>>> print(different2)
[55, 'string', 32.5, ['list_in_list', '55', 'string', '32*8']]

Такой список уже не является классическим массивом, поскольку он объединяет разнородные элементы: целое число, строку, число с плавающей запятой и список. То есть получается, списки включают в себя функции массивов, но их собственные функции шире.

Здесь и возникает логичный вопрос: а зачем вызывать отдельный модуль для создания массивов, если можно пользоваться списками, которые включают в себя обе функции? На это есть всего одна, но веская причина: вызываемые массивы отличаются большей компактностью и меньшим потреблением памяти. Это полезно при работе с ресурсоемкими приложениями и при выполнении низкоуровневых операций.

Работа с массивами

Далее мы не будем рассматривать классические списки (lists), по которым написаны отдельные статьи, а сосредоточимся на работе с вызываемыми массивами. Они импортируются при помощи модуля array. Важное замечание: функция array позволяет создавать массивы только из целочисленных значений и чисел с плавающей запятой. Также пока поддерживаются символы Unicode, но поддержку Юникода планируется убрать в следующих версиях Python (начиная с 4.0). Поэтому сосредоточимся на значениях int и float.

Импорт модуля array

Итак, функция array делает доступными массивы в программе на Python. Вызывается она по-разному, удобнее сделать так (минимизирует число последующих ошибок):

from array import *

Разумеется, эта команда, как и другие общие инструкции, должна быть указана в «шапке» кода, то есть в самом верху.

Создание массива

Чтобы создать массив, воспользуйтесь следующим шаблоном:

array_name = array(typecode,[ ])

Рассмотрим каждый элемент массива подробнее:

  • array_name — имя (можно задать любое, помня о правилах создания переменных в Python);
  • array — собственно функция;
  • typecode — тип хранимых данных (для целочисленных значений обычно указывают i, а для чисел с плавающей запятой чаще используют d);
  • [ ] — здесь через запятую перечисляются элементы массива.

Теперь попробуем создать простейший массив:

>>> from array import *
>>> integers = array('i',[1,2,3,4,5])
>>> print(integers)
array('i', [1, 2, 3, 4, 5])

Получилось. Давайте создадим массив с числами с плавающей запятой:

>>> from array import *
>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> print(floats)
array('d', [3.5, 7.2, 5.3, 9.5, 4.0])

А что будет, если в первом примере мы заменим целое число на число с плавающей запятой?

>>> integers = array('i',[1,2,3,4,5.2])
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    integers = array('i',[1,2,3,4,5.2])
TypeError: integer argument expected, got float

Предсказуемая ошибка, интерпретатор пишет, что ожидает целочисленный аргумент. С другой стороны:

>>> floats = array('d',[3.5,7.2,5.3,9.5,4])
>>> print(floats)
array('d', [3.5, 7.2, 5.3, 9.5, 4.0])

Здесь мы представили последнее число в виде целого, однако ошибки не случилось: интерпретатор смог привести его к нужному виду в выводе.

Операции с массивами

С массивами, как и со списками, можно выполнять различные операции.

  • Функция len() позволяет подсчитать количество элементов:
>>> integers = array('i',[1,2,3,4,5])
>>> print(len(integers))
5
  • Также можно индексировать элементы и выводить нужные (для этого используется конструкция print(array[number]):
>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> print(floats[0])
3.5
>>> print(floats[4])
4.0
>>> print(floats[1])
7.2

Обратите внимание, что нумерация в Python всегда начинается с нуля, поэтому, чтобы вызвать первый элемент, мы вводим print(floats[0]). Соответственно, пятый элемент идет под номером 4. А что будет, если попробовать вызвать элемент за границами массива?

>>> print(floats[5])
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    print(floats[5])
IndexError: array index out of range

Интерпретатор выдает сообщение об ошибке и пишет, что индекс как раз и находится за пределами. Иногда может потребоваться отрицательная индексация. В этом случае отсчет начинается с последнего элемента, который получает индекс -1:

>>> print(floats[-1])
4.0
>>> print(floats[-2])
9.5
>>> print(floats[-5])
3.5

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

  • Доступны и операции с циклами. Вот так выводится последовательность элементов при помощи цикла for:
>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> for d in floats:
print(d)

3.5
7.2
5.3
9.5
4.0

  • В отличие от строк, массивы и списки в Python изменяемы, поэтому допустимы и такие операции:
>>> floats[1] = 8.2
>>> print(floats)
array('d', [3.5, 8.2, 5.3, 9.5, 4.0])

Значение второго элемента было 7.2, но мы присвоили ему новое — 8.2.

  • Если значения элементов меняются, то, наверное, возможно добавить и новый элемент? Это делается при помощи метода append():
>>> integers = array('i',[1,2,3,4,5])
>>> integers.append(6)
>>> print(integers)
array('i', [1, 2, 3, 4, 5, 6])

Главное, чтобы добавляемый элемент относился к тому же типу данных, что и уже имеющиеся в массиве, иначе интерпретатор выдаст такую ошибку:

>>> integers.append(7.0)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
    integers.append(7.0)
TypeError: integer argument expected, got float

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

>>> floats = array('d',[3.5,7.2,5.3,9.5,4.0])
>>> floats.append(8)
>>> print(floats)
array('d', [3.5, 7.2, 5.3, 9.5, 4.0, 8.0])
  • Добавить в массив несколько элементов поможет метод extend(). Вводим далее в интерпретаторе:
>>> floats.extend([4.5,5.7,6.9])
>>> print(floats)
array('d', [3.5, 7.2, 5.3, 9.5, 4.0, 8.0, 4.5, 5.7, 6.9])
  • А если нам нужно вставить новый элемент на какую-то определенную позицию? Для этого предназначен метод insert(). Делается это так (используем всё тот же измененный массив с floats из примера выше):
>>> floats.insert(1,2.3)
>>> print(floats)
array('d', [3.5, 2.3, 7.2, 5.3, 9.5, 4.0, 8.0, 4.5, 5.7, 6.9])

Мы вставили число 2.3 на вторую позицию (помним про нумерацию, которая начинается с нуля, поэтому вторая позиция будет под номером 1).

  • Раз можно добавлять и вставлять элементы, то должен быть и метод их удаления. Он называется remove():
>>> floats.remove(7.2)
>>> print(floats)
array('d', [3.5, 2.3, 5.3, 9.5, 4.0, 8.0, 4.5, 5.7, 6.9])

А вот, что произойдет, если в массиве несколько элементов с одинаковым значением:

>>> integers = array('i',[11,12,13,14,15,11,11])
>>> integers.remove(11)
>>> print(integers)
array('i', [12, 13, 14, 15, 11, 11])

Удалилось только первое значение 11, а остальные остались в массиве. Для удаления элемента на конкретной позиции предназначен метод pop():

>>> integers = array('i',[11,12,13,14,15,11,11])
>>> integers.pop(5)
11
>>> print(integers)
array('i', [11, 12, 13, 14, 15, 11])

Число 11 на шестой позиции было удалено из массива.

Заключение

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

Contents

  • 1 Массивы в Python
    • 1.1 Списки (list)
      • 1.1.1 Создание
      • 1.1.2 Обращение к элементу
      • 1.1.3 Обход элементов
      • 1.1.4 Сравнение
      • 1.1.5 Размерность
      • 1.1.6 Преобразование
      • 1.1.7 Матрицы
    • 1.2 Массивы NumPy (Ndarray)
      • 1.2.1 Создание
      • 1.2.2 Тип значения элементов
      • 1.2.3 Обращение к элементам
      • 1.2.4 Атрибуты класса Ndarray
      • 1.2.5 Изменение размерности

В Python нет встроенного типа «массив», но вместо него можно использовать встроенный тип «список» (list). Также при использовании библиотеки NumPy можно создавать объект типа «массив» (Ndarray). Далее о каждом из этих двух вариантов подробнее.

Списки (list)

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

Создание

  • Создание пустого списка:
names = []
names = list()
  • Создание списка с элементами:
names = ['Иван', 'Женя', 'Ольга']
  • Создание списка на основе другого списка:
names = ['Иван', 'Женя', 'Ольга']
new_names = list(names)
  • Создание списка повторением какого-либо элемента или другого списка:
names = ['Иван', 'Женя', 'Ольга']
new_names = names * 2
  • Создание списка с помощью конструкции range():
numbers = list(range(10))

Функция range(10) возвращает числа от 0 до 9, на основе которых создаётся новый список.

Обращение к элементу

Обращение к элементу списка производится по индексу элемента:

names[0]

Индексы элементов начинаются с нулевого, то есть первый элемент списка имеет индекс «0», а второй — «1».

Обход элементов

Элементы списка можно обходить циклами for и while:

for name in names:
    print(name)

Сравнение

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

list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = list(range(10))

Размерность

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

names = [['Иван', 19],
        ['Женя', 20],
        ['Ольга', 21]]

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

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

names = [['Иван', 19],
        ['Женя', 20],
        ['Ольга', 21]]
names[1][0]

Преобразование

Двумерный список можно преобразовать в словарь с парами «ключ-значение»:

names = [['Иван', 19],
        ['Женя', 20],
        ['Ольга', 21]]
new_dict = dict(names)

Матрицы

Двумерный список является матрицей, которую визуально можно представить в следующем виде:

В данном примере переменная А содержит двумерный список, т.е. список списков, каждый из которых состоит из трёх элементов. Тип list в Python не поддерживает работу со списками как с матрицами, но, тем не менее, позволяет матрицы хранить.

Массивы NumPy (Ndarray)

Создание

Для использования класса Ndarray предварительно необходимо импортировать библиотеку numpy:

import numpy as np

Для создания массива используется функция модуля numpy — array():

import numpy as np

new_array = np.array(['Иван', 'Женя', 'Ольга'])

В первый параметр функции array() передаётся список, поэтому способов создания столько же, сколько способов создания списков. При передаче в параметр многомерного списка будет создан многомерный массив:

import numpy as np

new_array = np.array([['Иван', 19],
                        ['Женя', 20],
                        ['Ольга', 21]])

Тип значения элементов

В данном примере элементы массива были приведены к строковому типу, так как каждый список главного списка содержал строковое значение. Тип значения элементов массива можно переопределять при создании массива, указывая его вторым параметром функции array():

import numpy as np

new_array = np.array([['Иван', 19],
                        ['Женя', 20],
                        ['Ольга', 21]], dtype=np.str)

Обращение к элементам

Обращение к элементам массива Ndarray производится аналогично получение элемента в многомерном списке.

Атрибуты класса Ndarray

Далее рассмотрим атрибуты класса Ndarray:

  • ndim — число измерений (осей) массива;
  • shape — размерность массива. Это tuple, содержащий натуральные числа (n, m) — длины массива по каждой оси (n — высота, m — ширина). Число элементов кортежа shape равно ndim.
  • size — количество элементов в массиве, равно произведению всех элементов атрибута shape;
  • dtype — тип элементов массива. NumPy предоставляет возможность использовать как встроенные типы, например: bool_, character, int8, int16, int32, int64, float8, float16, float32, float64, complex64, object_, так и собственные типы данных, в том числе и составные;
  • itemsize — размер каждого элемента массива в байтах;
  • data — буфер, содержащий фактические элементы массива. Обычно не нужно использовать этот атрибут, так как обращаться к элементам массива проще всего с помощью индексов.

Изменение размерности

Размерность массива darray в Python можно изменять методом reshape():

import numpy as np

new_array = np.array([['Иван', 19],
                        ['Женя', 20],
                        ['Ольга', 21]], dtype=np.str)
new_array.reshape(2, 3)

При этом количество элементов должно позволять это сделать, т.е. произведение элементов атрибута shape до и после изменения размера должно быть одинаковым. К примеру, нельзя изменить размерность массива с (3, 4) на (2, 5), но можно изменить её на (2, 6).

Понравилась статья? Поделить с друзьями:
  • Массандра как правильно пишется
  • Массаж на английском языке как пишется
  • Масса нетто как пишется
  • Масса габаритные характеристики как пишется
  • Масс старт как пишется