tuple: Кортежи в Python

Содержание
Введение
Кортеж из списка
Неизменяемость
sorted
Похожие статьи

Введение

Кортеж в Python это:

Грубо говоря, кортеж - это список, который нельзя изменить. То есть, в кортеже есть только права на чтение. Это может быть защитой от случайных изменений.

Создать пустой кортеж:

t = tuple() print(t)

()

Кортеж может состоять из одного элемента:

# Это строка s = ("b") print(type(s)) print(s) # Это кортеж t = ("b",) print(type(t)) print(t)

Обратите внимание на запятую

<class 'str'> b <class 'tuple'> ('b',)

Кортеж из списка:

list_cities = ["benalmadena", "cordoba", "fuengirola", "malaga", "torremolinos"] tuple_cities = tuple(list_cities) print(type(list_cities)) print(type(tuple_cities)) print(tuple_cities)

<class 'list'> <class 'tuple'> ('benalmadena', 'cordoba', 'fuengirola', 'malaga', 'torremolinos')

К объектам в кортеже можно обращаться, как и к объектам списка, по порядковому номеру:

# By index print(tuple_cities[0])

benalmadena

Неизменяемость

Так как кортеж неизменяем, присвоить новое значение нельзя:

tuple_cities[1] = "barcelona"

Traceback (most recent call last): File "tuple_ex.py", line 18, in <module> tuple_cities[1] = "barcelona" TypeError: 'tuple' object does not support item assignment

TypeError можно обработать с помощью except

try: tuple_cities[1] = "barcelona" except TypeError: print("Can't change tuple")

Can't change tuple

sorted()

Функция sorted сортирует элементы кортежа по возрастанию и возвращает новый список с отсортированными элементами:

tuple_cities = ("cordoba", "fuengirola", "malaga", "torremolinos", "benalmadena") sorted_list_cities = sorted(tuple_cities) print(type(sorted_list_cities)) print(sorted_list_cities)

<class 'list'> ['benalmadena', 'cordoba', 'fuengirola', 'malaga', 'torremolinos']

Article author: Andrei Olegovich

Похожие статьи
Built-in Collections
Строки
f-string
format string
Списки []
list comprehension: Абстракция списка
Словари {:}
dict comprehension: Абстракция словаря
Множества {}
set comprehension: Абстракция множества
Кортежи ()
Протоколы
Итерация
Python
if, elif, else
Циклы

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: