How to modify Python List? What are the available ‘List’ functions?
Python List Functions:
Examples:
• index
• extend
• append
• insert
• remove
• clear
• pop
• count
• sort
• reverse
• copy
Examples:
fruits = ["Apple", "Orange", "Mango", "Grape"]
counts = [20, 25, 10, 15]
Index
Index: Values assigned to the elements in the list to organize the data is referred as ‘Index’.
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
print(fruits.index(“Orange”))
Results:
1
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
print(fruits.index(“Cherry”)
Results:
ValueError: ‘Mike’ is not in list
Modifying List Using Index Value:
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
fruits[1] = Cherry
print(fruits)
Results:
[‘Apple’, ’Cherry’, ‘Mango’, ‘Grape’]
Extend
Extend: Extends the existing List with another ‘List’.
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
counts = [20, 25, 10, 15]
fruits.extend(counts)
print(fruits)
Results:
[‘Apple’, ’Orange’, ‘Mango’, ‘Grape’, 20, 25, 10, 15]
Append
Append: Adds an item to the existing items in the List.
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
fruits.append(“Cherry”)
print(fruits)
Results:
[‘Apple’, ’Orange’, ‘Mango’, ‘Grape’, ‘Cherry’]
Insert
Insert: Inserts given item in to the List at a given index number. While using, we must provide index number and the item value.
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
fruits.insert(1, “Cherry”)
print(fruits)
Results:
[‘Apple’, ‘Cherry’, ’Orange’, ‘Mango’, ‘Grape’]
Remove
Remove: Removes the specified item from given List.
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
fruits.remove(“Orange”)
print(fruits)
Results:
[‘Apple’, ‘Mango’, ‘Grape’]
Clear
Clear: Clears all the elements from the given List.
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
fruits.clear()
print(fruits)
Results:
[ ]
Pop
Pop: Removes the last element from the List.
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
fruits.pop()
print(fruits)
Results:
[‘Apple’, ‘Orange’, ‘Mango’]
Count
Count: Provides the count of given element from the List.
Code:
fruits = ["Apple", "Orange", “Orange”, "Mango", "Grape"]
print(fruits.count(“Orange”))
print(fruits)
Results:
2
Sort
Sort: Arranges all the elements of a List in ascending order.
Example 1:
Code:
fruits = ["Apple", "Orange", "Mango", "Grape"]
fruits.sort()
print(fruits)
Results:
[‘Apple’, ‘Grape’, ‘Mango’, ‘Orange’]
Example 2:
Code:
counts = [20, 25, 10, 15]
counts.sort()
print(counts)
Results:
[15, 10, 25, 20]
Reverse
Reverse: Arranges all the elements of the List in reverse order.
Code:
counts = [20, 25, 10, 15]
counts.reverse()
print(counts)
Results:
[15, 10, 25, 20]
Copy
Copy: Copies the given List in to another List.
Code:
fruits = ["Apple", “Orange”, "Mango", "Grape"]
fruits2 = fruits.copy()
print(fruits2)
Results:
[‘Apple’, ‘Orange’, ‘Mango’, ‘Grape’]