fbpx

Tuples

In Python, a tuple is a collection of ordered and immutable elements, which can be of different data types. Tuples are represented by parentheses () with elements separated by commas. Tuples are essentially identical to lists, except for the fact that once a tuple is created, its elements cannot be modified, added or removed. 

You can access individual elements of a tuple using indexing, just like with lists. The first element has an index of 0, the second element has an index of 1, and so on. 

You can also slice a tuple using the same syntax as seen with lists.

See the following example:

				
					# create a tuple:
my_tuple = ('apple', 'banana', 'cherry', 1, 2, 3)

# indexing tuples:
print(my_tuple[0])   # Output: apple
print(my_tuple[3])   # Output: 1

# slicing tuples:
print(my_tuple[1:4])   # Output: ('banana', 'cherry', 1)

				
			

Replit Practice

Loading...