TUPLES

TUPLES

TUPLES

TUPLES

Tuples can be indexed and sliced just like lists. For example, to access the first element of the tuple, you can use the following code:

				
					my_tuple = (1, "hello", True) 
				
			

Tuples can be indexed and sliced just like lists. For example, to access the first element of the tuple, you can use the following code:

				
					first_element = my_tuple[0] 
				
			

Tuples are commonly used to group related values together. For example, a tuple might be used to represent a point in two-dimensional space, where the first element is the x-coordinate and the second element is the y-coordinate:

				
					point = (3, 4) 
				
			

Tuples can also be used to return multiple values from a function. For example, a function that calculates the minimum and maximum values in a list could return a tuple with two elements:

				
					def min_max(numbers):	
min_value = min(numbers) 
max_value = max(numbers)
 return (min_value, max_value) 

				
			

Overall, tuples are a useful data structure for storing collections of values that should not be modified once they are created.

Here are some basic tuple operations in Python:

  • Creating a tuple: A tuple is created by enclosing a sequence of comma-separated values within parentheses.
				
					my_tuple = (1, 2, 3) 
				
			
  • Accessing elements of a tuple: You can access elements of a tuple using indexing or slicing, just like with lists.
				
					my_tuple = (1, 2, 3)
 print(my_tuple[0]) # Output: 1
 print(my_tuple[1:]) # Output: (2, 3) 

				
			
  • Concatenating tuples: You can concatenate two tuples using the + operator.
				
					tuple1 = (1, 2, 3) 
tuple2 = (4, 5, 6)
 tuple3 = tuple1 + tuple2 
print(tuple3) # Output: (1, 2, 3, 4, 5, 6) 

				
			
  • Repetition of tuples: You can repeat a tuple by using the * operator.
				
					tuple1 = (1, 2, 3) 
tuple2 = tuple1 * 3 
print(tuple2) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3) 

				
			
  • Checking membership of a tuple: You can check if an element is present in a tuple using the in operator.
				
					my_tuple = (1, 2, 3) 
print(1 in my_tuple) # Output: True 
print(4 in my_tuple) # Output: False 

				
			
  • Finding the length of a tuple: You can find the length of a tuple using the len() function.
				
					my_tuple = (1, 2, 3) 
print(len(my_tuple)) # Output: 3 

				
			
  • Unpacking tuples: You can unpack the values of a tuple into separate variables.
				
					my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c)    # Output: 1 2 3

				
			
Join To Get Our Newsletter
Spread the love