Social Media

Image Slider

Showing posts with label Tuple. Show all posts
Showing posts with label Tuple. Show all posts
1/03/2019

Some methods related to tuple data structure:

max() and min(): These functions are used to calculate the max and minimum element from the tuple.
t=(1,2,3)
print(max(t)) # 3
print(min(t)) # 1

sum() function: This function is used to calculate the sum of all the elements of the tuple
t=(1,2,3)
print(sum(t)) # 6

len() : This function is used to calculate the length of the tuple.
t=[1,2,3,3,4]
print(len(t)) # 5

Accessing element of tuple using for loop:
We can access elements of tuple using for and while loop.
t=(1,2,3)
for x in t:
    print(x)

Accessing elements of tuple using while loop:
t=(1,2,4,4)
l=len(t)
i=0
while i<l:
    print(t[i])
    i+=1

Taking tuple from user:
t=tuple([eval(x) for x in input().split()])
Note: If we are giving string input here we have to use quotes in the input as well.

If we wan to store only integer in the tuple then we can do like this.
t=tuple([int(x) for x in input().split()])
print(t)

We can also use map() function for this purpose.
t=tuple(map(int,input().split()))
print(t)



Introduction to tuple data structure

Tuple is a sequential data structure.
As string and list tuple also support indexing and slicing.
The elements of tuple can be heterogeneous in nature.
Tuple is immutable data structure.
We have to use () to defining the tuple.
We cannot use append() method in tuple because it is immutable data structure.
example
t=(1,2,3,4)
print(type(t)) #tuple

Creating an empty tuple:
tuple() method can be used to create an empty tuple.
t=tuple()
print(type(t)) # tuple

Creating a tuple with single element:
t=(1,) # , is necessary if we are creating a tuple of single element, otherwise it will be int type.

Conversion of list into tuple:
We can also convert list data structure into tuple as shown below.
l=[1,2,3,4,5]
t=tuple(l)
print(t) # (1, 2, 3, 4, 5)