Python Tuples

Learning Python Day 6

Sarper Makas
2 min readJul 17, 2023
Python Tuples

A tuple is a built-in data structure in Python that allows you to store a collection of items. Tuples are similar to lists, but tuples are immutable, which means you cannot modify them once they are created.

Defining Tuples

Using Parantheses ()

The most common way to define a tuple in Python is by enclosing its elements in parentheses.

fruits = ('apple', 'banana', 'orange')

This creates a tuple named fruits containing three elements: 'apple', 'banana', and'orange'.

Using the tuple() Constructor

You can also create a tuple using the tuple() constructor. It can convert an iterable (such as a string, list, or another tuple) into a new tuple.

numbers = tuple([1, 2, 3, 4, 5])

Here, we pass a list of numbers to the tuple() constructor to create a tuple named numbers with the same elements.

Similarities with Lists

Indexing and slicing

You can access individual elements in a tuple using indexing and slicing operations, just like with lists.

fruits = ('apple', 'banana', 'orange', 'mango')

# Accessing individual elements
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: orange

# Negative indexing
print(fruits[-1]) # Output: mango
print(fruits[-3]) # Output: banana

# Slicing a subtuple
print(fruits[1:3]) # Output: ('banana', 'orange')
print(fruits[1:]) # Output: ('banana', 'orange', 'mango')
print(fruits[:3]) # Output: ('apple', 'banana', 'orange')
print(fruits[:]) # Output: ('apple', 'banana', 'orange', 'mango')

# Negative slicing
print(fruits[:-1]) # Output: ('apple', 'banana', 'orange')
print(fruits[-3:-1]) # Output: ('banana', 'orange')

Multiple data types

Tuples can contain elements of different data types, similar to lists.

mixed_tuple = (10, 'apple', True, 3.14)

print(mixed_tuple[0]) # Output: 10
print(mixed_tuple[1]) # Output: apple
print(mixed_tuple[2]) # Output: True
print(mixed_tuple[3]) # Output: 3.14

Length and Membership

You can use the len() function to get the length of a tuple, and the in keyword to check for membership.

fruits = ('apple', 'banana', 'orange')

# Length and membership
print(len(fruits)) # Output: 3
print('banana' in fruits) # Output: True

Iteration

You can iterate over the elements of a tuple using a loop, just like with lists.

fruits = ('apple', 'banana', 'orange')

# Iteration
for fruit in fruits:
print(fruit)

Differences from Lists

Immutability

Tuples are immutable, meaning you cannot modify their elements or their length once they are created. This is in contrast to lists, which are mutable.

Limited methods

Tuples have fewer built-in methods compared to lists since they cannot be modified. However, they do have methods such as count() and index().

fruits = ('apple', 'banana', 'orange')

# Tuple methods
print(fruits.index('banana')) # Output: 1
print(fruits.count('orange')) # Output: 1

--

--