- Append method:
The append() method is used to add an element to the end of a list. Here's an example:
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits)
Output: ['apple', 'banana', 'cherry', 'orange']
- Insert method:
The insert() method is used to add an element to a specific index in a list. Here's an example:
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'orange')
print(fruits)
Output: ['apple', 'orange', 'banana', 'cherry']
- Extend method:
The extend() method is used to add elements from one list to another list. Here's an example:
fruits = ['apple', 'banana', 'cherry']
colors = ['red', 'green', 'blue']
fruits.extend(colors)
print(fruits)
Output: ['apple', 'banana', 'cherry', 'red', 'green', 'blue']
- Remove method:
The remove() method is used to remove the first occurrence of an element in a list. Here's an example:
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits)
Output: ['apple', 'cherry']
- Pop method:
The pop() method is used to remove an element from a specific index in a list. If no index is specified, it removes the last element in the list. Here's an example:
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)
Output: ['apple', 'cherry']
- Clear method:
The clear() method is used to remove all elements from a list. Here's an example:
fruits = ['apple', 'banana', 'cherry']
fruits.clear()
print(fruits)
Output: []
- Index method:
The index() method is used to find the index of the first occurrence of an element in a list. Here's an example:
fruits = ['apple', 'banana', 'cherry']
index = fruits.index('banana')
print(index)
Output: 1
- Count method:
The count() method is used to count the number of occurrences of an element in a list. Here's an example:
fruits = ['apple', 'banana', 'cherry', 'banana']
count = fruits.count('banana')
print(count)
Output: 2
- sort(): This method is used to sort the list in ascending order.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.sort()
print(fruits)
Output: ['apple', 'banana', 'cherry']
- reverse(): This method is used to reverse the order of the items in the list.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits)
Output: ['cherry', 'banana', 'apple']
- copy(): This method is used to create a shallow copy of the list.
Example:
fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x)
Output: ['apple', 'banana', 'cherry']
In conclusion, the list methods in Python provide a convenient way to manipulate lists by adding, removing, or changing elements. These methods can be used to perform various operations on lists and can help in solving complex programming problems.
No comments:
Post a Comment