With Integers¶
In [1]:
# Creating a tuple with integers
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
(1, 2, 3, 4, 5)
In [2]:
# Accessing elements by index
print(my_tuple[0])
print(my_tuple[2])
1 3
In [3]:
# Slicing a tuple
print(my_tuple[1:4])
(2, 3, 4)
In [4]:
# Creating a new tuple with updated values
new_tuple = my_tuple[:2] + (99,) + my_tuple[3:]
print(new_tuple)
(1, 2, 99, 4, 5)
In [5]:
# Creating a new tuple without the element at index 2
new_tuple = my_tuple[:2] + my_tuple[3:]
print(new_tuple)
(1, 2, 4, 5)
In [6]:
# Tuple with duplicate elements
dup_tuple = (1, 2, 2, 3, 4, 4, 5)
unique_tuple = tuple(set(dup_tuple))
print(unique_tuple)
(1, 2, 3, 4, 5)
In [7]:
tuple1 = (1, 2, 3)
tuple2 = (3, 4, 5)
# Converting tuples to sets
set1 = set(tuple1)
set2 = set(tuple2)
# Union
union_set = set1.union(set2)
print(tuple(union_set))
# Intersection
intersection_set = set1.intersection(set2)
print(tuple(intersection_set))
# Difference
difference_set = set1.difference(set2)
print(tuple(difference_set))
# Symmetric Difference
sym_diff_set = set1.symmetric_difference(set2)
print(tuple(sym_diff_set))
(1, 2, 3, 4, 5) (3,) (1, 2) (1, 2, 4, 5)
With strings¶
In [8]:
# Creating a tuple
tuple1 = ("apple", "banana", "cherry")
tuple2 = ("hello", "world")
print(tuple1)
print(tuple2)
(''''apple'''', ''''banana'''', ''''cherry'''') (''''hello'''', ''''world'''')
In [9]:
# Accessing elements
print(tuple1[0])
print(tuple2[1])
apple world
In [10]:
# Updating a tuple
temp_list = list(tuple1)
temp_list[1] = "blueberry"
tuple1 = tuple(temp_list)
print(tuple1)
(''''apple'''', ''''blueberry'''', ''''cherry'''')
In [11]:
# Removing an element
temp_list = list(tuple1)
temp_list.remove("blueberry")
tuple1 = tuple(temp_list)
print(tuple1)
(''''apple'''', ''''cherry'''')
In [12]:
# Slicing a tuple
print(tuple1[0:2])
(''''apple'''', ''''cherry'''')
In [13]:
# Unique elements
tuple3 = ("apple", "banana", "apple", "cherry")
unique_elements = tuple(set(tuple3))
print(unique_elements)
(''''apple'''', ''''banana'''', ''''cherry'''')
In [14]:
# Union
set1 = set(tuple1)
set2 = set(tuple2)
union = tuple(set1.union(set2))
print(union)
# Intersection
intersection = tuple(set1.intersection(set2))
print(intersection)
# Difference
difference = tuple(set1.difference(set2))
print(difference)
# Symmetric Difference
symmetric_difference = tuple(set1.symmetric_difference(set2))
print(symmetric_difference)
(''''apple'''', ''''hello'''', ''''world'''', ''''cherry'''') () (''''apple'''', ''''cherry'''') (''''world'''', ''''apple'''', ''''hello'''', ''''cherry'''')
In [15]:
# Length of a tuple
print(len(tuple1))
# Checking if an item exists
print("apple" in tuple1)
# Concatenation
tuple4 = tuple1 + tuple2
print(tuple4)
# Repeating elements
tuple5 = tuple1 * 2
print(tuple5)
2 True (''''apple'''', ''''cherry'''', ''''hello'''', ''''world'''') (''''apple'''', ''''cherry'''', ''''apple'''', ''''cherry'''')