Thursday, May 4, 2023

#PYTHON(DAY8)tuple and it's methods

 

#PYTHON(DAY8)

Tuple and It’s methods

Tuple()

Example:

mytuple = ("apple", 1,2)
print(mytuple)
('apple',1,2)
x = (1,2,3,1,'sree',4)
print(x)
print(type(x))
(1,2,3,1,'sree',4)
<class 'tuple'>

Tuple Length

thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
3

creating an empty tuple

x = ()
print(x, len(x), type(x), sep = '\n')
()
0
<class 'tuple'>

creating a tuple with 2 elements

x = (1,)
print(x, len(x), type(x), sep = '\n')
(1,)
1
<class 'tuple'>

NOTE: tuple does not contain a single element

x = (1)
print(x, len(x), type(x), sep = '\n')

type-casting

a = [1,2,3]
x = tuple(a)
print(x, len(x), type(x), sep = '\n')
(1, 2, 3)
3
<class 'tuple'>
a = 'generic string'
x = tuple(a)
print(x, len(x), type(x), sep = '\n')
('g', 'e', 'n', 'e', 'r', 'i', 'c', ' ', 's', 't', 'r', 'i', 'n', 'g')
14
<class 'tuple'>

Access Tuple Items

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
banana

Negative Indexing

thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
cherry

Methods in tuple():

Range of Indexes

x = ('apple','banana','grapes','mango','orange','kiwi')
print([2:5])
('grapes','mango','orange')
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
('apple', 'banana', 'cherry', 'orange')

Range of Negative Indexes

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
('orange', 'kiwi', 'melon')

Check if Item Exists

thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Yes, 'apple' is in the fruits tuple

count()

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = thistuple.count(5)

print(x)
2

Unpacking a tuple

fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)
apple
banana
cherry

No comments:

Post a Comment

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...