Professional Documents
Culture Documents
List 3
List 3
Python lists are versatile, ordered, and mutable collections of items. They can store
a variety of data types, including integers, floats, strings, and other complex objects.
In this article, we will explore Python list methods, illustrating each with a real-time
example.
1. Creating a list:
fruits.append("kiwi")
# fruits: ['apple', 'banana', 'orange', 'grape', 'kiwi']
1. extend() : Appends items from another list to the end of the current list.
fruits.insert(1, "mango")
# fruits: ['apple', 'mango', 'banana', 'orange', 'grape', 'kiwi', 'strawberry', 'blueb
erry', 'raspberry']
1. remove() : Removes the first occurrence of a specified item from the list.
fruits.remove("banana")
# fruits: ['apple', 'mango', 'orange', 'grape', 'kiwi', 'strawberry', 'blueberry', 'ra
spberry']
1. pop() : Removes and returns an item at a specified index (defaults to the last
item if the index is not provided).
Lists 1
popped_fruit = fruits.pop(3)
# popped_fruit: 'grape'
# fruits: ['apple', 'mango', 'orange', 'kiwi', 'strawberry', 'blueberry', 'raspberry']
1. index() : Returns the index of the first occurrence of a specified item in the list.
index_of_kiwi = fruits.index("kiwi")
# index_of_kiwi: 3
fruit_count = fruits.count("orange")
# fruit_count: 1
1. sort() : Sorts the list in ascending order by default (can be customized using the
'key' and 'reverse' parameters).
fruits.sort()
# fruits: ['apple', 'blueberry', 'kiwi', 'mango', 'orange', 'raspberry', 'strawberry']
fruits.reverse()
# fruits: ['strawberry', 'raspberry', 'orange', 'mango', 'kiwi', 'blueberry', 'apple']
fruits_copy = fruits.copy()
# fruits_copy: ['strawberry', 'raspberry', 'orange', 'mango', 'kiwi', 'blueberry', 'ap
ple']
fruits.clear()
# fruits: []
Lists 2
In conclusion, Python lists are powerful and flexible data structures that offer a wide
range of built-in methods for manipulating and working with collections of items. By
understanding
Lists 3