Python 3 - Data types - Using a tuple

A tuple is like a list but without possibility to modify it.

We can see a tuple like something declared once to be sure data inside won't be modified in the future.

A bit like a #define or const in C/C++ or the final keyword in Java.

So there are only two methods for the tuple data type.
Let's see this in this Python 3 data type tuple tutorial.

In the form, there is also a difference with a list or a set, we declare it with parentheses:

tuple(item1, item2, item3)

Code

In the example below, we can see the count() and index() methods of the tuple data type.

value = "Hello"
myTuple = (value, 12, value, value)
nb = myTuple.count(value)
firstOccurrence = myTuple.index(value)

print("Number of \"" + value + "\" in the tuple: " + str(nb) + ".")
print("First occurrence of \"" + value + "\" is at index: " + str(firstOccurrence) + ".")

Result

Number of "Hello" in the tuple: 3.
First occurrence of "Hello" is at index: 0

A classic data type in Python 3. wink

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.