List and Tuples in Python
List Methods
Reverse a List
This program demonstrates how to reverse the elements of a list using the reverse() method.
# Program to reverse a list
my_list = [10, 20, 30, 40, 50]
my_list.reverse()
print("Reversed List:", my_list)
Pop an Element from a List
This program shows how to remove and return the last element using pop().
# Program to pop an element from the list
my_list = [1, 2, 3, 4, 5]
popped_element = my_list.pop()
print("Popped Element:", popped_element)
print("Updated List:", my_list)
Sort a List
This program demonstrates how to sort a list in ascending order using the sort() method.
# Program to sort a list
my_list = [30, 10, 20, 40, 50]
my_list.sort()
print("Sorted List:", my_list)
Remove a Specific Element from the List
This program shows how to remove a specific element using remove().
# Program to remove a specific element from the list
my_list = [10, 20, 30, 40, 50]
my_list.remove(30)
print("Updated List after removal:", my_list)
Append an Element to a List
This program demonstrates how to add an element to the end of the list using append().
# Program to append an element to the list
my_list = [1, 2, 3]
my_list.append(4)
print("List after appending:", my_list)
Insert an Element at a Specific Position
This program shows how to insert an element at a specific index using insert().
# Program to insert an element at a specific position
my_list = [10, 20, 40, 50]
my_list.insert(2, 30) # Insert 30 at index 2
print("List after insertion:", my_list)
Tuple Methods
Using count() method
The count() method returns the number of times a specified value appears in a tuple.
# Creating a tuple
my_tuple = (1, 2, 3, 4, 2, 2, 5)
# Counting occurrences of the number 2
count_of_2 = my_tuple.count(2)
# Displaying the result
print("The number 2 appears", count_of_2, "times in the tuple.")
Using index() method
The index() method returns the first index of the specified value in a tuple.
# Creating a tuple
my_tuple = ('apple', 'banana', 'cherry', 'banana', 'date')
# Finding the index of 'banana'
index_of_banana = my_tuple.index('banana')
# Displaying the result
print("The first occurrence of 'banana' is at index:", index_of_banana)