Python Tuples

Tuples are immutable lists and cannot be changed in any way once it is created.

Some of the characteristics features of Tuples are:

  • Tuples are defined in the same way as lists.
  • They are enclosed within parenthesis and not within square braces.
  • Elements of the tuple must have a defined order.
  • Negative indices are counted from the end of the tuple, just like lists.
  • Tuple also has the same structure where the values are separated by commas.

An example showing how to build tuples in Python:

Example:
tupl1 = ('computersc', 'IT', 'CSE');
tup2 = (6,5,4,3,2,1);

Accessing Values In Tuples

Programs to show how to access values in Tuples:

Example:
tupl1 = ('computersc', 'IT', 'CSE');
tupl2 = (1993, 2016);
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);

print ("tupl1[0]", tupl1[0])
print ("tupl3[2:4]", tupl3[2:4])
Output:
tupl1[0] computersc
tupl3[2:4] (6, 8)

Updating Tuples

They are immutable, i.e., the values can't be changed directly. So we can just update by joining tuples. Let's demonstrate this with an example:

Example:
tupl1 = (2, 3, 4);
tupl2 = ('ab', 'cd');
tupl3 = tupl1 + tupl2

print (tupl3)

This code snippet will execute a combination of two tuples using the "+" operator.

Output:
(2, 3, 4, 'ab', 'cd')

Delete Elements From Tuples

To delete a tuple, we can use the del-statement.

Syntax:
del tuple_name;
Example:
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);

del tupl3;

Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.