This tutorial will teach you about Python tuples and how to use them effectively.
You may want to make a list of elements that cannot be altered at any moment during the programme. Tuples make this possible.
A tuple is a list that is immutable. Immutable is a Python term for a value that cannot change. A tuple is an immutable list by definition.
How to Define a Tuple in Python?
A tuple is similar to a list, but instead of square brackets [, it uses parenthesis ().
The following example defines the rgb tuple:
rgb = ('red', 'green', 'blue')You can only access an individual element by its index once you’ve defined a tuple. For instance:
rgb = ('red', 'green', 'blue')
print(rgb[0])
print(rgb[1])
print(rgb[2])Output
red green blue
You can’t change the elements of a tuple because it’s immutable. The following example tries to alter the rgb tuple’s first element to ‘yellow’:
rgb = ('red', 'green', 'blue')
rgb[0] = 'yellow'It also leads to an error:
TypeError: ‘tuple’ object does not support item assignment
How to define a tuple with one element in Python?
You must insert a trailing comma after the first element to define a tuple with only one element. For instance:
numbers = (3,) print(type(numbers))
Output
<class ‘tuple’>
If the trailing comma is removed, the numbers’ type will be int, which stands for integer. It has a value of three. Python will not generate a tuple with the number 3 in it:
numbers = (3) print(type(numbers))
Output
<class ‘int’>
How to Assign a value to Tuple in Python?
You can assign a new tuple to a variable that refers a tuple, even though you can’t alter a tuple. For instance:
colors = ('red', 'green', 'blue')
print(colors)
colors = ('Cyan', 'Magenta', 'Yellow', 'black')
print(colors)
Leave a Reply