Python Tuplesupdated at May 09, 2024Tuples are used to store multiple items in a single variable.Tuple is one of 4 built-in data types in Python used to store collections of data,the other 3 are List,Set,and Dictionary,all with different qualities and usage.A tuple is a collection which is o... |
Python Tuples | ||||||
| ||||||
Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.
Tuple Items Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has index Ordered When we say that tuples are ordered, it means that the items have a defined order, and that order will not change. Unchangeable Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. Allow Duplicates Since tuples are indexed, they can have items with the same value:
Tuple Length To determine how many items a tuple has, use the
Create Tuple With One Item To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
Tuple Items - Data Types Tuple items can be of any data type:
A tuple can contain different data types:
type() From Python's perspective, tuples are defined as objects with the data type 'tuple':
The tuple() Constructor It is also possible to use the tuple() constructor to make a tuple.
Unpacking a Tuple When we create a tuple, we normally assign values to it. This is called "packing" a tuple:
But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking":
Using Asterisk If the number of variables is less than the number of values, you can add an
If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.
Loop Through a Tuple You can loop through the tuple items by using a
Loop Through the Index Numbers You can also loop through the tuple items by referring to their index number. Use the
Using a While Loop You can loop through the tuple items by using a Use the Remember to increase the index by 1 after each iteration.
Join Two Tuples To join two or more tuples you can use the
Multiply Tuples If you want to multiply the content of a tuple a given number of times, you can use the
Tuple Methods Python has two built-in methods that you can use on tuples.
Tags: Dictionary List Python Python Tuples Set Tuple Unpacking a Tuple | ||||||
| ||||||
| ||||||
|
|