Time to brush up next queued data structure. And its TUPLE.
PYTHON UNLEASH'D 08
Good day geeks!🤗
How to read this blog?
- Be ready with editor opened
- Give one and half min to each section i.e, intro and important
- run programs in between
INTRO
- Indexing ( from 0 OBV )
- Values separated by comma
- Parenthesis () encloses values [not mandatory, but convention]
- Remember parenthesis does not only make it tuple, I can make a tuple without using single bracket also (Inviting reader's views here in comments ⬇⬇) So there are other ways also besides parenthesis
() -> **parenthesis/round brackets**
[] -> **square brackets / big brackets**
{} -> **curly brackets**
- immutable
- heterogenous data
IMPORTANT
Similarities between list and tuple
- Values stored can be indexed
- Values are separated by comma inside
- contain any data type, any number of elements
Unlike lists, tuples are immutable
Creating tuple without parenthesis
Also, the brackets alone do not make an object into a tuple, but it’s not usual to define a integer like this: a = (2)
It’s more common to see: a = 2
It is better to follow what is easier for everyone to understand as long it follows rules.
a = (2)
print(type(a))
a = (1 , 2)
print(type(a))
Other than indexing, we can access tuple items by "unpacking"
See the demo below
Tuple1 = ("Geeks", "For", "Geeks")
# make sure number of var must be equal to total tuple elements
# This line unpack
# values of Tuple1
a, b, c = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
Concatenation of tuple
Say we have two tuples, tup1 and tup2
tup1 + tup2
is concatenation of both.
Slicing
Slicing rules are same as that for string and list. I request you to see below examples and read slicing on strings once from here
- Negative index can be used in slicing
Example
As tuples are immutable, we can not delete single element from tuple. However we can delete entire tuple at once, with help of del
keyword. Lets see how:
# Deleting a Tuple
Tuple1 = (0, 1, 2, 3, 4)
del Tuple1
print(Tuple1)
That's all for tuples.
There is a long list of methods which are unseen and unused for many of us, will see those once start practising.
If you have scrolled till here, do react to this post, and read other blogs in the series.
I am posting one blog everyday, follow for regular new blogs and leave your feedback in comments.
Thank you all for reading 🙌
Top comments (0)