About Tuple in Python with examples | For loop and tuple | count, index len function slicing | Nested lists are obtained using nested indexing

Tuple in Python explained

In this program, we will learn all about Python tuples. More specifically, what are tuples, how to get them, when to use them, and the different ways you should be familiar? A tuple in Python is related to a list. The difference between the two is that we cannot change the elements of a tuple as it is assigned whereas, in a list, the elements can be changed.

Tuple in Python

What is a tuple give an example?

tuple is a collection that is ordered and unchangeable. In Python tuples, You can access tuple items by referring to the index number, inside square 

Tuple Example:

# Tuple data structure

# tuple can store any data type

# most important tuples are immutable,

# one tuple is created you can’t update
# data inside a tuple

example = (‘one’,‘two’,‘three’,‘four’)

# no append,no insert,no pop, no remove

days = (‘monday’,‘tuesday’)

# tuple is faster than lists

Method

count, index len function slicing example[0]=1 # tuple do no assine number = (1,2,3,4,5,6,7.0)

What is nested list with examples?

In Python, the list which is inside the list is known as a nested list. Then how can we excess the nested list? Nested lists are obtained by using nested indexing.

Example to Excess Nested List:

my_list = [‘p’, ‘r’, ‘o’, ‘b’, ‘e’]

# Output: P

print (my_list [0]) # Output: o

print (my_list [2]) # Output: E

Print (my_list [4]) # Error! Only integers can be used for indexing

# my_list [4.0]

# Nested list

n_list = [“Happy”, [2,0,1,5]]

# Nested indexing

# Output: A

Print (n_list [0] [1])

# Output: 5

Print (n_list [1] [3])

How do you extract an element from a tuple? using for loop

A  for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for a keyword in other programming languages and works more like an iterative method as found in other object-orientated programming languages.
With the for loop, we can execute a set of statements, once for each item in a list, tuple, set, etc.
number = (1,2,3,4,5,6,7.0)
for i in number:
    print(i)

To learn More about tuple click Here

Recommended Post:

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.



Leave a Comment