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')
Or we can show it with commas;
tuple = "Python", "PHP", "Flutter", "Go"
print(tuple)
('Python', 'PHP', 'Flutter', 'Go')
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'>
Let's try using a comma;
tuple = "Python",
type(tuple)
<class 'tuple'>
How is Tuple Access?
Accessing tuple elements are the same as accessing elements with Lists
tuple = "Python", "PHP", "Flutter", "Go"
tuple[2]
Flutter
Let's do another example;
tuple = "Python", "PHP", "Flutter", "Go"
tuple[1:4]
('PHP', 'Flutter', 'Go')
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)
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']
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.
Top comments (0)