DEV Community

Cover image for Python tuple and tuple methods
Baransel
Baransel

Posted on

Python tuple and tuple methods

Sign up to my newsletter!.

What is Tuple?

If we explain what tuples are; Tuples are immutable dats types that can contain more than one data type, denoted by commas or parentheses.

How to Use Tuples?

Let's show it with an example;

tuple = ("Python", "PHP", "Flutter", "Go")
print(tuple)
('Python', 'PHP', 'Flutter', 'Go')
Enter fullscreen mode Exit fullscreen mode

Or we can show it with commas;

tuple = "Python", "PHP", "Flutter", "Go"
print(tuple)
('Python', 'PHP', 'Flutter', 'Go')
Enter fullscreen mode Exit fullscreen mode

But there is a very important point that we need to pay attention to here, if we are going to use a comma and if the tuple has one element, when we do not put a comma at the end, the interpreter perceives it as a String (character array).

Let me show you right now;

tuple = "Python"
type(tuple)
<class 'str'>
Enter fullscreen mode Exit fullscreen mode

Let's try using a comma;

tuple = "Python",
type(tuple)
<class 'tuple'>
Enter fullscreen mode Exit fullscreen mode

How is Tuple Access?

Accessing tuple elements are the same as accessing elements with Lists

tuple = "Python", "PHP", "Flutter", "Go"
tuple[2]
Flutter
Enter fullscreen mode Exit fullscreen mode

Let's do another example;

tuple = "Python", "PHP", "Flutter", "Go"
tuple[1:4]
('PHP', 'Flutter', 'Go')
Enter fullscreen mode Exit fullscreen mode

Tuple Methods

In the previous lessons of the Python lessons, I said that the tuple is an immutable data type, so the tuple can't be added, deleted, etc. If you want, let's show you with an example;

tuple = ("Python", "Flutter", "Go", "JavaScript", "PHP", "Java", "Python")
tuple[1] = "PHP"
print(tuple)
Enter fullscreen mode Exit fullscreen mode

We will come across a problem as follows. 'tuple' object does not support item assignment" tuple object does not support member assignment.

Let's list the methods with the dir() function;

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
 '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
 '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
 '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
 '__subclasshook__', 'count','index']
Enter fullscreen mode Exit fullscreen mode

Since methods such as __X__ are private methods, we will not look at them for now.

index Method:

Continue this post on my blog! Python tuple and tuple methods.

Sign up to my newsletter!.

Top comments (0)