Python Tuples


Tuples

Tuples can be used for the storage in one variable of multiple items.

A tuple is one of 4 built-in data types in Python that is used for the storage of data collections the other 3 are List, Set, and Dictionary, all having various properties and uses.

A tuple is an arranged and unchangeable collection.

Note :- Round brackets () are used to create tuples.

Example :- Create a simple tuple

mytuple = ("red", "green", "blue")
print(mytuple)

Output :-

('red', 'green', 'blue')

You can also search for these topics, python tuples programs, example for python tuples, symbol for tuples using python, syntax to define the python tuple, how to access tuples in python, access the python tuples first element, python append the tuples, when to use python tuples, what is python tuples.

Tuple Items

Multiple items are ordered, unmodified, and allow for duplicate values.

Multiple items are indexed, with the first item having index [0], the second item having index [1] and so on.

You can also search for these topics, python tuples item get, count, tuples python element wise comparison, how to index the tuples items in python, how to delete item in python tuples, item what does in python tuples, python tuples item when to use.

Ordered

When we state that tuples are sorted, we're referring to the fact that the items are in a specific sequence that will not change.

You can also search for these topics, python tuples ordered list, define the python tuples eigen values, python tuples all ordered combination, python tuples ordered algorithm, how to use ordered arguments using python tuples, collect the ordered the python tuples, how to use the python tuples choice and category.

Unchangeable

Tuples are immutable, which means that once they've been created, they can't be changed, added to, or removed.

You can also search for these topics, python immutable attribute and assignment with tuples, python bytes immutable with tuples, python tuple immutable collection, example for the python unchangeable tuples, python to define the error and key value with tuples.

Allow Duplicates

Tuples can have items with the same value because they're indexed :

Example :- A tuple with duplicate values :

mytuple = ("red", "green", "blue", "red", "blue")
print(mytuple)

Output :-

('red', 'green', 'blue', 'red', 'green')

You can also search for these topics, python allow duplicates keys, does python tuple allow duplicates, how to avoid the python duplicates, ways to allow duplicates the sorting in python, how to append the python allow the duplicates in python, based on conditions allowed duplicates the python tuples, allow the duplicates the detect in python, Example for python allow duplicates.

Tuple Length

Use the len() function to find out how many items are in a tuple :

Example :- The number of items in the tuple should be printed :

mytuple = tuple(("red", "green", "blue"))
print(len(mytuple))

Output :-

3

You can also search for these topics, python tuple length limit and size, python tuple max length, python tuple length what does, python tuple length when to use, python create tuple with length, execute the python tuple element and empty, check the equality of tuple length with python.

Check if Item Exists

The in keyword can be used to determine if a particular item is contained in a tuple.

Example :- Check to see if "green" appears in the tuple :

mytuple = ("red", "green", "blue")
if "green" in mytuple:
  print("Yes, 'green' is in the mytuple")

Output :-

Yes, 'green' is in the mytuple

You can also search for these topics, python check if item exists in multiple list, how to check if an item already exists in a list in python, check if element exists python, see if item exists python.

Create Tuple With One Item

You must add a comma to create a tuple with only a single item, otherwise, Python will not recognize that as a tuple.

Example :- One item tuple, remember the comma :

mytuple = ("red",)
print(type(mytuple))

# NOT a tuple

mytuple = ("red")
print(type(mytuple))

Output :-

<class 'tuple'>
<class 'str'>

You can also search for these topics, python create tuple with one item by value, python Create Tuple With One Item by index, declaration of python Create Tuple With One Item, python Create Tuple With One Item element.

Tuple Items - Data Types

Any data type can be used in a tuple item :

Example 1 :- Creating multiple tuples with different datatypes like string, int and boolean.

tuple1 = ("red", "green", "blue")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False)

print(tuple1)
print(tuple2)
print(tuple3)

Output :-

('red', 'green', 'blue')
(1, 5, 7, 9, 3)
(True, False)

A tuple can have different data typesof data in it.

Example 2 :- Strings, numbers, and boolean values are all included in this tuple :

tuple1 = (111, "abc", 5.5, True)

print(tuple1)

Output :-

(111, 'abc', 5.5, True)

You can also search for these topics, tuple data type in python, how tuple items are different data types in python, python list the tuple items with datatypes, example for python tuple items with data types.

type()

Python defines tuples as objects with the 'tuple' type of data.

<class 'tuple'>

Example :- What is the data type of a tuple?

mytuple = ("red", "green", "blue")

print(type(mytuple))

Output :-

<class 'tuple'>

You can also search for these topics, python tuple type() not working , return value of python tuple type, python tuple type arguments, type the builtin using python tuple, how to change the type in python tuple, comparison of python tuple type, check the type of python tuple, python tuple keyerror type, Example for type of tuples using python, What is the data type of a python tuple?.

The tuple() Constructor

The tuple() constructor can also be used to generate a tuple.

Example :- Using the tuple() method to make a tuple :

mytuple = tuple(("red", "green", "blue"))
print(mytuple)

Output :-

('red', 'green', 'blue')

You can also search for these topics, python the tuple costructor key value, check the key exists in python tuple constructor, keep ordering the tuple constructor using python, how to create the python tuple constructor, example for tuple constructor using python.

Access Tuple Items

Index numbers in square brackets can be used to access tuple items.

Example :- The third item in the tuple should be printed :

mytuple = ("red", "green", "blue")
print(mytuple[2])

Output :-

blue

Note: The first item has an index of 0.

You can also search for these topics, python access tuple element by name, how to access the tuple in python, python access tuple items with default, get tuple first element python, Example for access tuple items.

Negative Indexing

Indexing in the negative direction involves starting at the end of a list.

-1 refers to the last item, -2 refers to the second last item etc.

Example :- The tuple's last item should be printed :

mytuple = ("red", "green", "blue")
print(mytuple[-1])

Output :-

blue

You can also search for these topics, python negative indexing is not supported, how does negative indexing work in python, why negative indexing is used in python, does python allow negative indexing, negative indexing in python example.

Range of Indexes

You can provide a range of indexes by defining where to begin and where to end the range.

Any range supplied will produce a tuple with the specified elements in it as its return value.

Example 1 :- The third, fourth, and fifth items should be returned :

mytuple = ("red", "green", "blue", "orange", "gray", "white", "black")
print(mytuple[2:5])

# This will return the items from position 2 to 5.

# Remember that the first item is position 0, 
# and note that the item in position 5 is NOT included

Output :-

('blue', 'orange', 'gray')

Note: Index 2 (included) is the starting point for the search. Index 5 is the ending point (not included).

Remember that the first item has an index of 0.

It is not necessary to specify a start value for the range to begin at the first item :

Example 2 :- "gray" is NOT included in this example, which returns all things from the beginning to the end range :

mytuple = ("red", "green", "blue", "orange", "gray", "white", "black")

print(mytuple[:4])

Output :-

('red', 'green', 'blue', 'orange')

The range will extend to the end of the list if the end value is not specified :

Example 3 :- As you can see, this example returns the elements from "orange" to the end of the tuple :

mytuple = ("red", "green", "blue", "orange", "gray", "white", "black")

print(mytuple[3:])

Output :-

('orange', 'gray', 'white', 'black')

You can also search for these topics, python range out of index, which for loop has range of similar indexes, python list range of indexes, range of indexes python example.

Python - Update Tuples

It is impossible to add or remove items from a tuple once it has been created because tuples are unchangeable once they are created.

However, there are several workarounds that can be used.

You can also search for these topics, python update tuples value, python modify tuple element, how to update tuple in python, update tuple python append element.

Change Tuple Values

When creating a tuple, its values can't be changed. They are immutable, as they are sometimes termed.

There is, however, a way to get around this issue. Just follow the below steps to change a tuple values :

  1. Create a tuple.
  2. Convert tuple as list using list() method.
  3. Change the value in the list.
  4. Convert the list as new tuple using tuple() method.

Exmaple :- Changing a tuple value :

x = ("red", "green", "blue")
y = list(x)
y[1] = "orange"
x = tuple(y)

print(x)

Output :-

("red", "orange", "blue")

You can also search for these topics, python tuple replace values, how to change value in tuple python, change tuple value python how to access, Example for python change tuple values.

Add Items

There is no built-in append() method for tuples because they are immutable, but there are various ways to put things into tuple.

1. To work around this, you can change the tuple into a list, add your item(s), and then convert it back into a tuple.

Example 1 :- Converting the tuple to a list, then add "orange" before returning it to a tuple :

mytuple = ("red", "green", "blue")
y = list(mytuple)
y.append("orange")
mytuple = tuple(y)

print(mytuple)

Output :-

('red', 'green', 'blue', 'orange')

2. Tuples can be added together by adding one to another. As tuples can be added to tuples, creating a new tuple containing the item(s) and adding it to the existing tuple is an option.

Example 2 :- Add items from another tuple :

x = ("red", "green", "blue")
y = ("white", "black")
x += y

print(x)

Output :-

('red', 'green', 'blue', 'white', 'black')

Note :- A comma must be used after the item when producing a tuple with only one item, or else the tuple won't be recognised as such.

You can also search for these topics, python add item to empty tuple, python tuple insert item, python tuple add new element, python tuple add element wise, write a python program to add an item in a tuple.

Remove Items

Note: Items in a tuple can't be removed.

You can't remove things from a tuple because it's unchangeable, but you can use the same workaround we used for modifying and adding tuple elements in the above program.

Example 1 :- Convert the tuple to a list, remove "red", and convert it back to a tuple :

mytuple = ("red", "green", "blue")
y = list(mytuple)
y.remove("red")
mytuple = tuple(y)

print(mytuple)

Output :-

('green', 'blue')

or You can also delete the entire tuple.

Example 2 :- It is possible to delete the tuple completely by using the del keyword :

mytuple = ("red", "green", "blue")
del mytuple
print(mytuple) #this will raise an error because the tuple no longer exists

Output :-

Traceback (most recent call last):
File "demo_tuple_del.py", line 3, in < module>
print(mytuple) #this will raise an error because the tuple no longer exists
NameError: name 'mytuple' is not defined

You can also search for these topics, python remove item from list without error, how to remove first item in list python, remove last item python, python delete last item in dictionary, Example for python remove items.

Unpacking a Tuple

It's common for us to assign values to a tuple after we generate it. A tuple is "packed" in this way.

Extracting values from a tuple is called unpacking.

Example :- Packing a tuple :

colors = ("red", "green", "blue")

print(colors)

Output :-

('red', 'green', 'blue')

Python allows us to extract the values back into variables, though. "Unpacking" is the term for this process :

Example 2 :- Unpacking a tuple :

colors = ("red", "green", "blue")

(r, g, b) = colors

print(r)
print(g)
print(b)

Output :-

red
green
blue

Note :- When there are more variables than values in a tuple, you'll need to use a "asterisk" to aggregate the remaining values into one list.

You can also search for these topics, python unpack tuple in fuction call, python unpack tuple with one element, how to unpack tuples in python, python unpack tuple into arguments, unpack multiple tuples python

Using Asterisk*

Variable names can be prefixed with a * to indicate that a list of values will be assigned to them if there are fewer variables than values.

Example 1 :- Create a asterisk variable called "b" for the rest of the data :

colors = ("red", "green", "blue", "white", "black")

(r, g, *b) = colors

print(r)
print(g)
print(b)

Output :-

red
green
['blue', 'white', 'black']

Python will assign values to a variable until the number of values left equals the number of variables remaining if an asterisk is added to a variable name other than the final.

Example 2 :- Please add the "g" variable a value list :

colors = ("red", "green", "blue", "white", "black")

(r, *g, b) = colors

print(r)
print(g)
print(b)

Output :-

red
['green', 'blue', 'white']
black

You can also search for these topics, python asterisk parameters, python using asterisk meaning, examples of using asterisk, using asterisk in search, print letters using asterisk in python.

Python - Loop Through a Tuples

It is also possible to loop through the tuple items using a for-loop.

Example :- Iterate through the elements and print out the tuple values.

mytuple = ("red", "green", "blue")
for x in mytuple:
  print(x)

Output :-

red
green
blue

You can also search for these topics, python loop through tuple with index, for loop through tuple python, how to loop through tuple python, loop through tuple python value.

Loop Through the Index Numbers

It's also possible to loop through the tuple items by referring to their index number.

You may generate a suitable iterable by using the range() and len() functions to create a list.

Example :- All items can be printed by referring to their corresponding index number :

mytuple = ("red", "green", "blue")
for i in range(len(mytuple)):
  print(mytuple[i])

Output :-

red
green
blue

You can also search for these topics, python loop through index number factorial, loop through index number python multidimensional, loop with index in python, index number in for loop python.

Using a While Loop

Using a while loop, you may iterate through the list elements.

To get the length of the tuple, use the len() function, then begin at 0 and loop through the tuple members using their indexes.

Remember to increment the index by one after each iteration.

Example :- Using a while loop to iterate through all of the index numbers, print all items :

mytuple = ("red", "green", "blue")
i = 0
while i < len(mytuple):
  print(mytuple[i])
  i = i + 1

Output :-

red
green
blue

You can also search for these topics, python tuple use while loop with example, python tuple use while loop how to use, tuple use while loop python not working, tuple use while loop python tutorial.

Python - Join Tuples

The + operator can be used to merge two or more tuples :

Join Two Tuples

You can use the + operator to join two tuples into one.

Example :- Join two tuples

tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2
print(tuple3)

Output :-

('a', 'b', 'c', 1, 2, 3)

You can also search for these topics, python merge two tuple, python join two tuple generate, how to merge two tuples in python, join two tuples of the last element are same, Example for python Join Two Tuples.

Multiply Tuples

The * operator can be used to multiply the contents of a tuple by a specified number of times.

Exmaple :- In this case, the colors tuple is multiplied by 2 :

colors = ("red", "green", "blue")
colors2 = colors * 2

print(colors2)

Output :-

('red', 'green', 'blue', 'red', 'green', 'blue')

You can also search for these topics, python tuple multiple assignment, python multiply tuple element, python create tuple from multiple lists, python tuple multiple values, python tuple with multiple item.