Python Data Structures (Tuple)

Selin Yazıcıoğlu
3 min readJun 16, 2022

--

Hello guys! I will mention the tuple which is data structures in this article. I will code on Visual Studio Code also I will show you on Github. Okay, let’s start!

Tuple

Tuple has many features. These are,

  • Tuple can be accessed by index,
  • Ordered,
  • Tuples cannot be modified, so items cannot be added or deleted after they are created.
  • () is defined in parentheses, and elements are separated by commas.
  • It may contain different types of data.
  • It can have two items with the same value. It can be duplicate data.

I would like to give some examples related to tuples.

Indexes in Tuple

I want to show you how indexes work in tuples.

  • If we want to create an empty tuple, then we should do,

tuple = ()

  • This example shows from zero to five indexes. Here we see that zero is included, but 5 is not.
my_tuple = (0,1,2,3,4,5,6,7,8,9)
print(my_tuple[:5])
Output:
(0, 1, 2, 3, 4)
  • To find which index “Gilbert” is in the tuple we should do,
my_tuple = ("Anne with an E", "Gilbert", "Rosemary")
print(my_tuple.index("Gilbert"))
Output:
1
  • Searching,
my_tuple = (1,2,3,4,1,2,7,6,8,2)
print(my_tuple.index(2,4,7)) # searches for 2 between 4 and 7
Output:
5
  • Changing,

Tuples cannot be modified. Tuples cannot be changed. If there is a list in the tuple, we can only change it within the list.

mix_tuple = ("Selin", 303, True, [1,2,3])mix_tuple[3][0] = 8print(mix_tuple)
Output:
('Selin', 303, True, [8, 2, 3])

If we want to change elements in a tuple then,

Firstly, we should change the tuple to list.

my_tuple = (1,2,3,4)
print(my_tuple)
temp_list = list(my_tuple)
print(temp_list)
Output:
(1, 2, 3, 4)
[1, 2, 3, 4]

For example, we wanted to change the third index to “Bootcamp”,

temp_list[3] = "Bootcamp"
print(temp_list)
Output:
[1, 2, 3, 'Bootcamp']

In conclusion, we changed to list to a tuple again.

my_tuple = tuple(temp_list)
print("Type", type(my_tuple))
print(my_tuple)
Output:
Type <class 'tuple'>
(1, 2, 3, 'Bootcamp')

Copying Tuple

I explained to give an example.

my_tuple = (1,2,3,4)
my_tuple2 = my_tuple
print(my_tuple2)
Output:
(1, 2, 3, 4)
my_tuple = (1,2,3,4)
tuple3 = my_tuple2 + my_tuple
print(tuple3)
Output:
(1, 2, 3, 4, 1, 2, 3, 4)

Attention!

I would like to give some important information about tuples. If you want to create a tuple you should be careful when creating it.

my_tuple = ("Selin")
my_tuple1 = ("Selin",)
print(type(my_tuple))
print(type(my_tuple1))
Output:
<class 'str'>
<class 'tuple'>

If you don’t put a comma, it doesn’t perceive as a tuple.

I hope while you’re reading my article you can enjoy it!

See you on another topic :)

If you want, you can follow me at these links:

--

--