Answers for "tuple methods"

52

what is a tuple in python

# A tuple is a sequence of immutable Python objects. Tuples are
# sequences, just like lists. The differences between tuples
# and lists are, the tuples cannot be changed unlike lists and
# tuples use parentheses, whereas lists use square brackets.
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = "a", "b", "c", "d";

# To access values in tuple, use the square brackets for
# slicing along with the index or indices to obtain value
# available at that index.
tup1[0] # Output: 'physics'
Posted by: Guest on March-03-2020
0

tuple methods

my_tuple = ('a','p','p','l','e',)

# len() : get the number of elements in a tuple
print(len(my_tuple))

# count(x) : Return the number of items that is equal to x
print(my_tuple.count('p'))

# index(x) : Return index of first item that is equal to x
print(my_tuple.index('l'))

# repetition
my_tuple = ('a', 'b') * 5
print(my_tuple)

# concatenation
my_tuple = (1,2,3) + (4,5,6)
print(my_tuple)

# convert list to a tuple and vice versa
my_list = ['a', 'b', 'c', 'd']
list_to_tuple = tuple(my_list)
print(list_to_tuple)

tuple_to_list = list(list_to_tuple)
print(tuple_to_list)

# convert string to tuple
string_to_tuple = tuple('Hello')
print(string_to_tuple)
Posted by: Guest on August-03-2021
0

python tuple methods

count(x) : Returns the number of times 'x' occurs in a tuple
index(x) : Searches the tuple for 'x' and returns the position of where it was first found
Posted by: Guest on February-22-2021

Python Answers by Framework

Browse Popular Code Answers by Language