# Concatenation: Joining two tuplesa = (1,2,3)b = (4,5,6)concat_result = a + bprint('a+b:', concat_result)# Repetition: Repeating a list multiple timesc = ('Hi!',)repet_result = c *3print('c*3', repet_result)# Membership: Check if a value exists in a tupled = a + b + cprint('d:', d)print('\'Hi!\' in d:', 'Hi!'in d)print('7 in d:', 7in d)
# Iterationexample = ('C','Java','Python','C#','JavaScript')print('Tuple example items:')for language in example:print(language)print('--')# Indexingprint('Index 1:', example[1])print('Last Value:', example[-1])# Slicingprint('Backwards:', example[::-1])print('Every other:', example[::2])print('From 1 to end:', example[1:])print('From 1 to 3:', example[1:3])
Tuple example items:
C
Java
Python
C#
JavaScript
--
Index 1: Java
Last Value: JavaScript
Backwards: ('JavaScript', 'C#', 'Python', 'Java', 'C')
Every other: ('C', 'Python', 'JavaScript')
From 1 to end: ('Java', 'Python', 'C#', 'JavaScript')
From 1 to 3: ('Java', 'Python')
Built-in Functions with Tuple
example = ('C','Java','Python','C#','JavaScript')print('Length:', len(example))print('Minimum value:', min(example))print('Maximum value:', max(example))print('--')word ='Hello'array = [1,2,3,4]array_array = [[1],[2,3],[4]]print('String to Tuple:', tuple(word))print('List to Tuple:', tuple(array))print('2D array to Tuple:', tuple(array_array))print('--')array_array[0][0] ='p'print(array_array)# Note: don't have mutable data type as items in a tuple ...
Length: 5
Minimum value: C
Maximum value: Python
--
String to Tuple: ('H', 'e', 'l', 'l', 'o')
List to Tuple: (1, 2, 3, 4)
2D array to Tuple: ([1], [2, 3], [4])
--
[['p'], [2, 3], [4]]
Tuple Comprehension
# Tuple of Even values from 1 to 100even_tup =tuple(i for i inrange(1,101) if i %2==0)print(even_tup)