Содержание
- 1 Множества
- 2 Recommended Posts:
- 3 Access Tuple Items
- 4 Задания для самопроверки
- 5 Python NumPy
- 6 Creating a Tuple
- 7 Creating a Tuple
- 8 Индексация кортежей
- 9 Python. Урок 8. Кортежи (tuple)
- 10 Access Tuple Items
- 11 Python NumPy
- 12 Python Arithmetic Operators
- 13 Удаление элементов кортежа
- 14 Кортежи
- 15 Зачем использовать кортеж вместо списка?
- 16 Python NumPy
- 17 Deleting a Tuple
- 18 Recommended Posts:
- 19 Delete Tuple Elements
Множества
Множества это неупорядоченные коллекции объектов не содержащие дубликатов. Пустое множество создаётся функцией или круглыми скобками . Множества неупорядоченны поэтому к элементам множества нельзя обратится по индексу. Множества, за исключением frozen set, изменяемы.
>>> basket = >>> basket_set = set() >>> basket_set set() >>> basket_set.update(basket) >>> basket_set {‘pear’, ‘orange’, ‘apple’, ‘banana’} >>> basket_set.add(«clementine») >>> basket_set {‘pear’, ‘orange’, ‘apple’, ‘banana’, ‘clementine’} >>> basket_set.remove(«apple») >>> basket_set {‘pear’, ‘orange’, ‘banana’, ‘clementine’}
1 2 3 4 5 6 7 8 9 10 11 12 13 |
>>>basket=’apple’,’orange’,’apple’,’pear’,’orange’,’banana’ >>>basket_set=set() >>>basket_set set() >>>basket_set.update(basket) >>>basket_set {‘pear’,’orange’,’apple’,’banana’} >>>basket_set.add(«clementine») >>>basket_set {‘pear’,’orange’,’apple’,’banana’,’clementine’} >>>basket_set.remove(«apple») >>>basket_set {‘pear’,’orange’,’banana’,’clementine’} |
Recommended Posts:
- Python | Remove tuples from list of tuples if greater than n
- Python | Convert string tuples to list tuples
- Python | Count tuples occurrence in list of tuples
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Find the tuples containing the given element from a list of tuples
- Python | Remove duplicate tuples from list of tuples
- Python | Combining tuples in list of tuples
- Python | How to Concatenate tuples to nested tuples
- Tuples in Python
- Python | Get sum of tuples having same first value
- Python | Min and Max value in list of tuples
- Python — AND operation between Tuples
- Python — Union of Tuples
- Python | How to get Subtraction of tuples
- Python | All possible N combination tuples
- Python | Compare tuples
- Python | Addition of tuples
- Python | Elementwise AND in tuples
- Python | Chunk Tuples to N
- Python | Index Maximum among Tuples
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
Example
Print the second item in the tuple:
thistuple = («apple», «banana», «cherry») print(thistuple)
Example
Print the last item of the tuple:
thistuple = («apple», «banana», «cherry») print(thistuple)
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = («apple», «banana», «cherry», «orange», «kiwi», «melon», «mango») print(thistuple)
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = («apple», «banana», «cherry», «orange», «kiwi», «melon», «mango») print(thistuple)
Задания для самопроверки
1. Дан кортеж:
p = («+792345678», «+792345478», «+792355678», «+592345678», «+392345678», «+7923456558»)
Нужно вывести все номера, начинающиеся с «+7».
2. Имеется набор оценок в виде строки:
«Оценки: 5, 4, 3, 4, 2, 4, 5, 4»
Необходимо создать кортеж, в котором находились бы только оценки в виде целых чисел:
(5, 4, 3, 4, 2, 4, 5, 4)
3. Вывести значения кортежа:
((1,2,3),(3,4,5),(6,7,8))
в виде таблицы:
1 – 2 – 3 4 – 5 – 6 7 – 8 – 9
Видео по теме
Python 3 #1: установка и запуск интерпретатора языка
Python 3 #2: переменные, оператор присваивания, типы данных
Python 3 #3: функции input и print ввода/вывода
Python 3 #4: арифметические операторы: сложение, вычитание, умножение, деление, степень
Python 3 #5: условный оператор if, составные условия с and, or, not
Python 3 #6: операторы циклов while и for, операторы break и continue
Python 3 #7: строки — сравнения, срезы строк, базовые функции str, len, ord, in
Python 3 #8: методы строк — upper, split, join, find, strip, isalpha, isdigit и другие
Python 3 #9: списки list и функции len, min, max, sum, sorted
Python 3 #10: списки — срезы и методы: append, insert, pop, sort, index, count, reverse, clear
Python 3 #11: списки — инструмент list comprehensions, сортировка методом выбора
Python 3 #12: словарь, методы словарей: len, clear, get, setdefault, pop
Python 3 #13: кортежи (tuple) и операции с ними: len, del, count, index
Python 3 #14: функции (def) — объявление и вызов
Python 3 #15: делаем «Сапер», проектирование программ «сверху-вниз»
Python 3 #16: рекурсивные и лямбда-функции, функции с произвольным числом аргументов
Python 3 #17: алгоритм Евклида, принцип тестирования программ
Python 3 #18: области видимости переменных — global, nonlocal
Python 3 #19: множества (set) и операции над ними: вычитание, пересечение, объединение, сравнение
Python 3 #20: итераторы, выражения-генераторы, функции-генераторы, оператор yield
Python 3 #21: функции map, filter, zip
Python 3 #22: сортировка sort() и sorted(), сортировка по ключам
Python 3 #23: обработка исключений: try, except, finally, else
Python 3 #24: файлы — чтение и запись: open, read, write, seek, readline, dump, load, pickle
Python 3 #25: форматирование строк: метод format и F-строки
Python 3 #26: создание и импорт модулей — import, from, as, dir, reload
Python 3 #27: пакеты (package) — создание, импорт, установка (менеджер pip)
Python 3 #28: декораторы функций и замыкания
Python 3 #29: установка и порядок работы в PyCharm
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random Random Intro Data Distribution Random Permutation Seaborn Module Normal Distribution Binomial Distribution Poisson Distribution Uniform Distribution Logistic Distribution Multinomial Distribution Exponential Distribution Chi Square Distribution Rayleigh Distribution Pareto Distribution Zipf Distribution
NumPy ufunc ufunc Intro ufunc Create Function ufunc Simple Arithmetic ufunc Rounding Decimals ufunc Logs ufunc Summations ufunc Products ufunc Differences ufunc Finding LCM ufunc Finding GCD ufunc Trigonometric ufunc Hyperbolic ufunc Set Operations
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses , separated by commas. The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).
Output
() (1, 2, 3) (1, 'Hello', 3.4) ('mouse', , (1, 2, 3))
A tuple can also be created without using parentheses. This is known as tuple packing.
Output
(3, 4.6, 'dog') 3 4.6 dog
Creating a tuple with one element is a bit tricky.
Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.
Output
<class 'str'> <class 'tuple'> <class 'tuple'>
Creating a Tuple
In Python, tuples are created by placing sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of data sequence.
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
Python program to demonstrate addition of elements in a Tuple.
filter_none
editclose
play_arrow
linkbrightness_4code
chevron_right
filter_none
Output:
Initial empty Tuple: () Tuple with the use of String: ('Geeks', 'For') Tuple using List: (1, 2, 4, 5, 6) Tuple with the use of function: ('G', 'e', 'e', 'k', 's')
Creating a Tuple with Mixed Datatypes.
Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.). Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
filter_none
editclose
play_arrow
linkbrightness_4code
chevron_right
filter_none
Output:
Tuple with Mixed Datatypes: (5, 'Welcome', 7, 'Geeks') Tuple with nested tuples: ((0, 1, 2, 3), ('python', 'geek')) Tuple with repetition: ('Geeks', 'Geeks', 'Geeks') Tuple with a loop ('Geeks',) (('Geeks',),) ((('Geeks',),),) (((('Geeks',),),),) ((((('Geeks',),),),),)
Индексация кортежей
Каждый элемент в кортеже, как и в любой другой упорядоченной последовательности, можно вызвать по его индексу.
Каждому элементу присваивается уникальный индекс (целое число). Индексация начинается с 0.
Вернёмся к кортежу coral и посмотрим, как проиндексированы его элементы:
‘blue coral’ | ‘staghorn coral’ | ‘pillar coral’ | ‘elkhorn coral’ |
1 | 2 | 3 |
Первый элемент (‘blue coral’) идёт под индексом 0, а последний (‘elkhorn coral’) – под индексом 3.
При помощи индекса можно вызвать каждый отдельный элемент кортежа. Например:
Диапазон индексов данного кортежа – 0-3. Таким образом, чтобы вызвать любой из элементов в отдельности, можно сослаться на индекс.
Если вызвать индекс вне диапазона данного кортежа (в данном случае это индекс больше 3), Python выдаст ошибку:
Также в кортежах можно использовать отрицательные индексы; для этого подсчёт ведётся в обратном направлении с конца кортежа, начиная с -1. Отрицательная индексация особенно полезна, если вы хотите определить последний элемент в конце длинного кортежа.
Кортеж coral будет иметь такие отрицательные индексы:
‘blue coral’ | ‘staghorn coral’ | ‘pillar coral’ | ‘elkhorn coral’ |
-4 | -3 | -2 | -1 |
Чтобы запросить первый элемент, ‘blue coral’, по отрицательному индексу, нужно ввести:
Элементы кортежа можно склеивать со строками при помощи оператора +:
Также оператор + позволяет склеить два кортежа (больше информации об этом – дальше в статье).
Python. Урок 8. Кортежи (tuple)
Данный урок посвящен кортежам (tuple) в Python
Основное внимание уделено вопросу использования кортежей, почему иногда лучше применять их, а не списки, рассмотрены способы создания и основные приемы работы с кортежами. Также затронем тему преобразования кортежа в список и обратно
Что такое кортеж (tuple) в Python?
Кортеж (tuple) – это неизменяемая структура данных, которая по своему подобию очень похожа на список. Как вы наверное знаете, а если нет, то, пожалуйста, ознакомьтесь с седьмым уроком, список – это изменяемый тип данных. Т.е. если у нас есть список a = и мы хотим заменить второй элемент с 2 на 15, то мы может это сделать, напрямую обратившись к элементу списка.
>>> a = >>> print(a) >>> a = 15 >>> print(a)
С кортежем мы не можем производить такие операции, т.к. элементы его изменять нельзя.
>>> b = (1, 2, 3) >>> print(b) (1, 2, 3) >>> b = 15 Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> b = 15 TypeError: 'tuple' object does not support item assignment
Зачем нужны кортежи в Python?
Существует несколько причин, по которым стоит использовать кортежи вместо списков. Одна из них – это обезопасить данные от случайного изменения. Если мы получили откуда-то массив данных, и у нас есть желание поработать с ним, но при этом непосредственно менять данные мы не собираемся, тогда, это как раз тот случай, когда кортежи придутся как нельзя кстати. Используя их в данной задаче, мы дополнительно получаем сразу несколько бонусов – во-первых, это экономия места. Дело в том, что кортежи в памяти занимают меньший объем по сравнению со списками.
>>> lst = >>> tpl = (10, 20, 30) >>> print(lst.__sizeof__()) 32 >>> print(tpl.__sizeof__()) 24
Во-вторых – прирост производительности, который связан с тем, что кортежи работают быстрее, чем списки (т.е. на операции перебора элементов и т.п
будет тратиться меньше времени). Важно также отметить, что кортежи можно использовать в качестве ключа у словаря
Создание, удаление кортежей и работа с его элементами
Создание кортежей
Для создания пустого кортежа можно воспользоваться одной из следующих команд.
>>> a = () >>> print(type(a)) <class 'tuple'> >>> b = tuple() >>> print(type(b)) <class 'tuple'>
Кортеж с заданным содержанием создается также как список, только вместо квадратных скобок используются круглые.
>>> a = (1, 2, 3, 4, 5) >>> print(type(a)) <class 'tuple'> >>> print(a) (1, 2, 3, 4, 5)
При желании можно воспользоваться функцией tuple().
>>> a = tuple((1, 2, 3, 4)) >>> print(a) (1, 2, 3, 4)
Доступ к элементам кортежа
Доступ к элементам кортежа осуществляется также как к элементам списка – через указание индекса. Но, как уже было сказано – изменять элементы кортежа нельзя!
>>> a = (1, 2, 3, 4, 5) >>> print(a) 1 >>> print(a) (2, 3) >>> a = 3 Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> a = 3 TypeError: 'tuple' object does not support item assignment
Удаление кортежей
Удалить отдельные элементы из кортежа невозможно.
>>> a = (1, 2, 3, 4, 5) >>> del a Traceback (most recent call last): File "<pyshell#26>", line 1, in <module> del a TypeError: 'tuple' object doesn't support item deletion
Но можно удалить кортеж целиком.
>>> del a >>> print(a) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> print(a) NameError: name 'a' is not defined
Преобразование кортежа в список и обратно
На базе кортежа можно создать список, верно и обратное утверждение. Для превращения списка в кортеж достаточно передать его в качестве аргумента функции tuple().
>>> lst = >>> print(type(lst)) <class 'list'> >>> print(lst) >>> tpl = tuple(lst) >>> print(type(tpl)) <class 'tuple'> >>> print(tpl) (1, 2, 3, 4, 5)
Обратная операция также является корректной.
>>> tpl = (2, 4, 6, 8, 10) >>> print(type(tpl)) <class 'tuple'> >>> print(tpl) (2, 4, 6, 8, 10) >>> lst = list(tpl) >>> print(type(lst)) <class 'list'> >>> print(lst)
P.S.
Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
<<< Python. Урок 7. Работа со списками (list) Python. Урок 9. Словари (dict)>>>
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
Example
Print the second item in the tuple:
thistuple = («apple», «banana», «cherry») print(thistuple)
Example
Print the last item of the tuple:
thistuple = («apple», «banana», «cherry») print(thistuple)
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = («apple», «banana», «cherry», «orange», «kiwi», «melon», «mango») print(thistuple)
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = («apple», «banana», «cherry», «orange», «kiwi», «melon», «mango») print(thistuple)
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random Random Intro Data Distribution Random Permutation Seaborn Module Normal Distribution Binomial Distribution Poisson Distribution Uniform Distribution Logistic Distribution Multinomial Distribution Exponential Distribution Chi Square Distribution Rayleigh Distribution Pareto Distribution Zipf Distribution
NumPy ufunc ufunc Intro ufunc Create Function ufunc Simple Arithmetic ufunc Rounding Decimals ufunc Logs ufunc Summations ufunc Products ufunc Differences ufunc Finding LCM ufunc Finding GCD ufunc Trigonometric ufunc Hyperbolic ufunc Set Operations
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
Operator | Description | Example |
---|---|---|
+ Addition | Adds values on either side of the operator. | a + b = 30 |
— Subtraction | Subtracts right hand operand from left hand operand. | a – b = -10 |
* Multiplication | Multiplies values on either side of the operator | a * b = 200 |
/ Division | Divides left hand operand by right hand operand | b / a = 2 |
% Modulus | Divides left hand operand by right hand operand and returns remainder | b % a = 0 |
** Exponent | Performs exponential (power) calculation on operators | a**b =10 to the power 20 |
// | Floor Division — The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) − | 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0 |
Удаление элементов кортежа
Удалить отдельный элемент из кортежа нельзя:
>>> del tup3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object doesn't support item deletion
Но — ничего не мешает создать новый, без ненужного элемента:
>>> tup1 = (1, 2, 3) >>> del tup1 >>> tup2 = tup1 >>> print tup2 (1, 2)
Что бы удалить кортеж полностью — используется тот же оператор del:
>>> tup = ('physics', 'chemistry', 1997, 2000); >>> >>> print tup; ('physics', 'chemistry', 1997, 2000) >>> del tup; >>> print "After deleting tup : " After deleting tup : >>> print tup; Traceback (most recent call last): File "<stdin>", line 1, in <module> NameE
Кортежи
Последнее обновление: 09.03.2017
Кортежи предоставляют удобный способ для работы с набором значений, который был добавлен в версии C# 7.0.
Кортеж представляет набор значений, заключенных в круглые скобки:
var tuple = (5, 10);
В данном случае определен кортеж tuple, который имеет два значения: 5 и 10. В дальнейшем мы можем обращаться к каждому из этих значений через поля с названиями Item. Например:
static void Main(string[] args) { var tuple = (5, 10); Console.WriteLine(tuple.Item1); // 5 Console.WriteLine(tuple.Item2); // 10 tuple.Item1 += 26; Console.WriteLine(tuple.Item1); // 31 Console.Read(); }
В данном случае тип определяется неявно. Но мы ткже можем явным образом указать для переменной кортежа тип:
(int, int) tuple = (5, 10);
Так как кортеж содержит два числа, то в определении типа нам надо указать два числовых типа. Или другой пример определения кортежа:
(string, int, double) person = ("Tom", 25, 81.23);
Первый элемент кортежа в данном случае представляет строку, второй элемент — тип int, а третий — тип double.
Мы также можем дать названия полям кортежа:
var tuple = (count:5, sum:10); Console.WriteLine(tuple.count); // 5 Console.WriteLine(tuple.sum); // 10
Теперь чтобы обратиться к полям кортежа используются их имена, а не названия Item1 и Item2.
Мы даже можем не использовать переменную для определения всего кортежа, а использовать отдельные переменные для его полей:
static void Main(string[] args) { var (name, age) = ("Tom", 23); Console.WriteLine(name); // Tom Console.WriteLine(age); // 23 Console.Read(); }
В этом случае с полями кортежа мы сможем работать как с переменными, которые определены в рамках метода.
Использование кортежей
Кортежи могут передаваться в качестве параметров в метод, могут быть возвращаемым результатом функции, либо использоваться иным образом.
Например, одной из распространенных ситуаций является возвращение из функции двух и более значений, в то время как функция можно возвращать только одно значение. И кортежи представляют оптимальный способ для решения этой задачи:
static void Main(string[] args) { var tuple = GetValues(); Console.WriteLine(tuple.Item1); // 1 Console.WriteLine(tuple.Item2); // 3 Console.Read(); } private static (int, int) GetValues() { var result = (1, 3); return result; }
Здесь определен метод , который возвращает кортеж. Кортеж определяется как набор значений, помещенных в круглые скобки. И в данном случае мы возвращаем кортеж из двух элементов типа int, то есть два числа.
Другой пример:
static void Main(string[] args) { var tuple = GetNamedValues(new int[]{ 1,2,3,4,5,6,7}); Console.WriteLine(tuple.count); Console.WriteLine(tuple.sum); Console.Read(); } private static (int sum, int count) GetNamedValues(int[] numbers) { var result = (sum:0, count: 0); for (int i=0; i < numbers.Length; i++) { result.sum += numbers; result.count++; } return result; }
И также кортеж может передаваться в качестве параметра в метод:
static void Main(string[] args) { var (name, age) = GetTuple(("Tom", 23), 12); Console.WriteLine(name); // Tom Console.WriteLine(age); // 35 Console.Read(); } private static (string name, int age) GetTuple((string n, int a) tuple, int x) { var result = (name: tuple.n, age: tuple.a + x); return result; }
НазадВперед
Зачем использовать кортеж вместо списка?
Тем, кто уже успел познакомиться со списками в Python, может показаться не очевидным смысл использования кортежей. Ведь фактически, списки могут делать всё то же самое и даже больше. Это вполне естественный вопрос, но, разумеется, у создателей языка найдётся на него ответ:
- Неизменяемость – именно это свойство кортежей, порой, может выгодно отличать их от списков.
- Скорость – кортежи быстрее работают. По причине неизменяемости кортежи хранятся в памяти особым образом, поэтому операции с их элементами выполняются заведомо быстрее, чем с компонентами списка.
- Безопасность – неизменяемость также позволяет им быть идеальными кандидатами на роль констант. Константы, заданные кортежами, позволяют сделать код более читаемым и безопасным.
- Использование tuple в других структурах данных – кортежи применимы в отдельных структурах данных, от которых python требует неизменяемых значений. Например ключи словарей (dicts) должны состоять исключительно из данных immutable-типа.
Кроме того, кортежи удобно использовать, когда необходимо вернуть из функции несколько значений:
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random Random Intro Data Distribution Random Permutation Seaborn Module Normal Distribution Binomial Distribution Poisson Distribution Uniform Distribution Logistic Distribution Multinomial Distribution Exponential Distribution Chi Square Distribution Rayleigh Distribution Pareto Distribution Zipf Distribution
NumPy ufunc ufunc Intro ufunc Create Function ufunc Simple Arithmetic ufunc Rounding Decimals ufunc Logs ufunc Summations ufunc Products ufunc Differences ufunc Finding LCM ufunc Finding GCD ufunc Trigonometric ufunc Hyperbolic ufunc Set Operations
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. Entire tuple gets deleted by the use of del() method.Note- Printing of Tuple after deletion results to an Error.
filter_none
editclose
play_arrow
linkbrightness_4code
chevron_right
filter_none
Built-In Methods
Built-in Function | Description |
---|---|
all() | Returns true if all element are true or if tuple is empty |
any() | return true if any element of the tuple is true. if tuple is empty, return false |
len() | Returns length of the tuple or size of the tuple |
enumerate() | Returns enumerate object of tuple |
max() | return maximum element of given tuple |
min() | return minimum element of given tuple |
sum() | Sums up the numbers in the tuple |
sorted() | input elements in the tuple and return a new sorted list |
tuple() | Convert an iterable to a tuple. |
Recent Articles on Tuple
Tuples Programs
- Print unique rows in a given boolean Strings
- Program to generate all possible valid IP addresses from given string
- Python Dictionary to find mirror characters in a string
- Generate two output strings depending upon occurrence of character in input string in Python
- Python groupby method to remove all consecutive duplicates
- Convert a list of characters into a string
- Remove empty tuples from a list
- Reversing a Tuple
- Python Set symmetric_difference()
- Convert a list of Tuples into Dictionary
- Sort a tuple by its float element
- Count occurrences of an element in a Tuple
- Count the elements in a list until an element is a Tuple
- Sort Tuples in Increasing Order by any key
- Namedtuple in Python
Useful Links-
- Output of Python Programs
- Recent Articles on Python Tuples
- Multiple Choice Questions – Python
- All articles in Python Category
My Personal Notes arrow_drop_up Save
Recommended Posts:
- Python | Remove tuples from list of tuples if greater than n
- Python | Convert string tuples to list tuples
- Python | Count tuples occurrence in list of tuples
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Find the tuples containing the given element from a list of tuples
- Python | Remove duplicate tuples from list of tuples
- Python | Combining tuples in list of tuples
- Python | How to Concatenate tuples to nested tuples
- Tuples in Python
- Python | Get sum of tuples having same first value
- Python | Min and Max value in list of tuples
- Python — AND operation between Tuples
- Python — Union of Tuples
- Python | How to get Subtraction of tuples
- Python | All possible N combination tuples
- Python | Compare tuples
- Python | Addition of tuples
- Python | Elementwise AND in tuples
- Python | Chunk Tuples to N
- Python | Index Maximum among Tuples
Improved By : nikhilaggarwal3, awpkalsi
Delete Tuple Elements
Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −
#!/usr/bin/python tup = ('physics', 'chemistry', 1997, 2000); print tup; del tup; print "After deleting tup : "; print tup;
This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −
('physics', 'chemistry', 1997, 2000) After deleting tup : Traceback (most recent call last): File "test.py", line 9, in <module> print tup; NameError: name 'tup' is not defined
С этим читают
- Методы строк в python
- Несколько подводных камней статической типизации в python
- Встроенные функции python: какие нужно знать и на какие не стоит тратить время
- Tuples / кортежи в python
- Python write file/ read file
- Python string isupper islower upper lower functions example
- Traceback в python
- Numpy.nonzero
- Учебник по sqlite3 в python
- Python урок 4. списки или массивы в питоне