You are on page 1of 3

Lists

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 = ["apple", "banana", "orange", "grape"]

1. append() : Adds an item to the end of the list.

fruits.append("kiwi")
# fruits: ['apple', 'banana', 'orange', 'grape', 'kiwi']

1. extend() : Appends items from another list to the end of the current list.

berries = ["strawberry", "blueberry", "raspberry"]


fruits.extend(berries)
# fruits: ['apple', 'banana', 'orange', 'grape', 'kiwi', 'strawberry', 'blueberry', 'r
aspberry']

1. insert() : Inserts an item at a specific index in the 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

1. count() : Returns the number of occurrences of a specified item in the list.

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']

1. reverse() : Reverses the order of the items in the list.

fruits.reverse()
# fruits: ['strawberry', 'raspberry', 'orange', 'mango', 'kiwi', 'blueberry', 'apple']

1. copy() : Returns a shallow copy of the list.

fruits_copy = fruits.copy()
# fruits_copy: ['strawberry', 'raspberry', 'orange', 'mango', 'kiwi', 'blueberry', 'ap
ple']

1. clear() : Removes all items from the list.

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

You might also like