Python3 Tutorial - 7 (Tuples)

Welcome to CCP,
Hello you,

so,
we left off with dictionaries, i know you guys were in suspense about the Immutable list i discussed or gave a hint about in previous tutorial,

but hey ! what is Immutable ?
Well, immutable refers to a material or here, a data structure which can't be be changed,

till now, we've been studying about lists and dictionaries which are mutable and their elements can be changed like this:


now we will be seeing a new data type: tuples
theses are defined b/w "()" and not b/w "[]" or "{}",
like this:



here:
error belongs to "Error", number belongs to 404 and message belongs to "Page Not Found",
almost similarly, we can also unpack lists like this:


we can declare as many elements in tuple but can't change them,
if we try to do so, we'll get an error like this:


In this case, the error message after TypeError is self-explanatory,
these messages are used to debug our code in case it misbehaves,

And tuples can be indexed also just like lists as we can see in the above picture how we printed tuple[0] as 10,

This process of calling the values in lists and tuples by their indexes (0, 1, 2...) and calling values of dictionaries by their keys is known as INDEXING

These types of immutable values and data structures helps a data not getting modified accidentally by The Programmers,
and tuples are also iterable, that means we can go through all elements in any tuple using a for loop,

example:

my_tuple = (1, 2, 3, 5)
for elem in my_tuple:
    print(elem)

# outputs:
# 1
# 2
# 3
# 5

So, i hope tuples are clear for you,

UP NEXT:

We will meet a different data structure called Sets
A Mixture of lists and dictionaries,
weird huh ?

MEET YOU IN NEXT PART !

Comments

  1. Can lists and tuples be unpacked similarly ?

    ReplyDelete

Post a Comment