Python tuples
- Tuple is a ordered sequential data structure in python.
- Tuple is immutable hence can't be modified once created.
- Tuple stores the data in a sequential manner.
- Tuple items can be accessed with an index.
- The index starts from
0
to length of tuple - 1
- Tuple also supports negative indexing (i.e -1, -2, etc).
create a tuple for fruits
fruits = ("apple", "apple", "banana", "cherry")
print(fruits)
# Output: ('apple', 'apple', 'banana', 'cherry')
tuples can store different data types
elements = ("apple", 100, 3.5, {"name": "Anji"})
print(elements)
# Output: ('apple', 100, 3.5, {'name': 'Anji'})
find length of a tuple
fruits = ("apple", "banana", "cherry")
print(len(fruits))
# Output: 3
create tuple with one item
one_item = ("hello",)
print(one_item)
# Output: ('hello',)
iterate through tuple with for loop
fruits = ("apple", "banana", "cherry")
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
concatenate two tuples with "+" operator
t1 = (1,2,3)
t2 = (4,5,6)
t3 = t1 + t2
print(t3)
# Output: (1, 2, 3, 4, 5, 6)
slicing a tuple
- slice syntax: tuple[start : stop : step]
- default start is
0
- default end is
length of tuple - 1
t = (1,2,3,4,5,6,7,8,9,10)
t1 = t[0:5]
print(t1)
# Output: (1, 2, 3, 4, 5)
t2 = t[5:]
print(t2)
# Output: (6, 7, 8, 9, 10)
t3 = t[1:8:2]
# Output: (2, 4, 6, 8)
convert other iterable data type to tuple
items = [1,2,3,4]
print(type(items))
# Output: <class 'list'>
t1 = tuple(items)
print(type(t1))
# Output: <class 'tuple'>
data = {"one": 1, "two": 2}
t2 = tuple(data)
print(t2)
# Output: ('one', 'two')
print(type(t2))
# Output: <class 'tuple'>
count an element in tuple
t = (1,2,3,4,5,6,3,10,6)
element = 3
print(t.count(element))
# Output: 2
get index of an element in tuple
- syntax: tuple.index(element, start_index, end_index)
- default start index
0
- default end index
length of tuple - 1
t = (1,2,3,4,5,6,3,10,6)
element = 4
print(t.index(element))
# Output: 3
print(t.index(element, 2))
# Output: 3
print(t.index(element, 2, 9))
# Output: 3
unpack a tuple
t1 = (1,2,3)
a, b, c = t1
print(a, b, c)
# Output: 1 2 3
t2 = (1,2,3,4,5,6,7,8)
one, two, *other_numbers = t2
print(one, two, other_numbers)
# Output: 1 2 [3, 4, 5, 6, 7, 8]
References