Page 71 - Touhpad Ai
P. 71
Using remove() Function
The remove function deletes the first occurrence of the specified value from the list.
# Removing element using remove() function
fruits.remove("cherry")
print(fruits)
Output:
['kiwi', 'blueberry', 'banana', 'orange', 'strawberry', 'apple', 'mango']
Using pop() Function
The pop() function removes and returns the element at the specified position (index). If no index is specified, it removes
and returns the last element.
# Removing element using pop() function
fruits.pop(3)
print(fruits)
Output:
['kiwi', 'blueberry', 'banana', 'strawberry', 'apple', 'mango']
Operations on Tuple
Similar to the list, we can also perform the same operations on the tuples.
Creating a Tuple
You can create a tuple by placing all the elements inside parentheses (), separated by commas.
city = ("Delhi", "Madrid", "Chennai", "Rome")
Indexing in Tuple
Tuples are indexed similarly to lists, with both positive and negative indexing.
# Accessing elements using positive indexing
print(city[0]) # Output: Delhi
print(city[1]) # Output: Madrid
# Accessing elements using negative indexing
print(city[-1]) # Output: Rome
print(city[-2]) # Output: Chennai
Immutability
Tuples cannot be modified after they are created, which means their elements remain unchanged. Nevertheless, you can
combine two or more tuples to form a new tuple.
The following line would generate an error
city[1] = "New York"
A tuple cannot be edited, But, a new tuple can be created by using an existing tuple (city) and a new value (New York).
city2 = city + ("New York",) #comma indicates that it is a tuple
print(city2) # Output: city = ("Delhi", "Madrid", "Chennai", "Rome", "New York")
Basic Concepts of Artificial Intelligence 69

