Python List Functions and Examples
# 1. len() – Returns number of elements
fruits = ['apple', 'banana', 'cherry']
print(len(fruits)) # Output: 3
# 2. max() – Returns the largest element
numbers = [4, 7, 2, 9]
print(max(numbers)) # Output: 9
# 3. min() – Returns the smallest element
print(min(numbers)) # Output: 2
# 4. sum() – Returns the sum of all numeric elements
print(sum(numbers)) # Output: 22
# 5. list() – Converts other data type to list
text = "ABC"
print(list(text)) # Output: ['A', 'B', 'C']
# 6. append() – Adds element at the end
[Link]('mango')
print(fruits) # Output: ['apple', 'banana', 'cherry', 'mango']
# 7. insert() – Adds element at given position
[Link](1, 'orange')
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry', 'mango']
# 8. extend() – Adds elements from another list
more_fruits = ['kiwi', 'grape']
[Link](more_fruits)
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry', 'mango', 'kiwi', 'grape']
# 9. remove() – Removes first occurrence of an item
[Link]('banana')
print(fruits) # Output: ['apple', 'orange', 'cherry', 'mango', 'kiwi', 'grape']
# 10. pop() – Removes and returns element by index (default last)
item = [Link](2)
print(item) # Output: cherry
print(fruits) # Output: ['apple', 'orange', 'mango', 'kiwi', 'grape']
# 11. clear() – Removes all elements from the list
temp = [1, 2, 3]
[Link]()
print(temp) # Output: []
# 12. index() – Returns index of first occurrence
nums = [10, 20, 30, 40, 20]
print([Link](20)) # Output: 1
# 13. count() – Returns how many times value appears
print([Link](20)) # Output: 2
# 14. sort() – Sorts the list in ascending order
[Link]()
print(nums) # Output: [10, 20, 20, 30, 40]
# 15. reverse() – Reverses the order of elements
[Link]()
print(nums) # Output: [40, 30, 20, 20, 10]
# 16. copy() – Returns a shallow copy of the list
copy_nums = [Link]()
print(copy_nums) # Output: [40, 30, 20, 20, 10]