202 Views | Read Time 2 minutes |
Welcome back, folks. This is the continuation part of the python tutorial series. In this article, we are going to focus on Tupple. If you are just starting up, I will recommend you to go through the Python Tutorial Part 1 and Part 2.
- Tuples is a more efficient version of list that you can not modify.
- Tuples are not mutable elements.
- Tuples is different from lists we
can’t use sort(), append() and reverse()
functions with tuples
- They are more efficient because they
can’t be modified so they don’t allocate as many memory as lists
- Use list if you needed, but if you can use a tuple instead lists, it would be better especially if you will use that variable for a brief moment only
A tuple can have any number of items, and they may be of
different types. Let us see different examples for tuples:
- Making Empty tuple:
- Tuple with different items:
You can access to tuple items the same as lists, by adding tuple name and element need to access an index in square brackets.
And it gives output as seen in the figure
In tuples you can’t replace elements of the tuple, you can do it in lists but you can’t do it in tuples it will give you an error.
But you can add to tuples together as shown in the following
And it gives the sum of that two tuples
Loop through tuple:
can also loop through a tuple to find the items trough that tuples
You will get an output for that code every item in that tuple
as shown in figure
Length of the tuple
You can know the length of the tuple using len()
function, look at the following figure to know how to use it
And gives an integer output with length of the tuple
Basic tuple operations:
|(56, 78, 24) + (1, 2, 4)||(56, 78, 24, 1, 2, 4)||Concatenation|
|(‘Hi’)*4||(‘Hi’, ‘Hi’, ‘Hi’, ‘Hi’)||Repetition|
|8 in (1, ‘Ahmed’, 8)||True||Membership|
|for x in (1, 2, 3): print x||1 2 3||Iteration|
I hope you like this article. Please let us know in the below comments section if you have any comments or concerns regarding this article.
Join To Our Newsletter
You are welcome