Lists are Python’s most flexible data structure. You can create them empty or filled with values, and they can hold strings, numbers, or even other lists. This makes them perfect for organizing collections of related data.
empty_list = list()
print(len(empty_list)) # 0
fruits = ['banana', 'orange', 'mango', 'lemon']
vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
print("Fruits:", fruits)
print("Number of fruits:", len(fruits))
Accessing Items
Each item in a list has an index starting from 0. Negative indices count backward from the end, which is useful when you want the last item without knowing the length.
fruits = ['banana', 'orange', 'mango', 'lemon']
print(fruits[0]) # banana
print(fruits[-1]) # lemon
print(fruits[-2]) # mango
Slicing Lists
Slicing lets you extract portions of a list. By specifying start and end indices, you can create sublists without altering the original.
fruits = ['banana', 'orange', 'mango', 'lemon']
print(fruits[1:3]) # ['orange', 'mango']
print(fruits[:]) # all fruits
print(fruits[-3:]) # ['orange', 'mango', 'lemon']
Modifying Lists
Lists are mutable, meaning you can change their contents after creation.
fruits[0] = 'Avocado'
fruits[1] = 'Apple'
print(fruits) # ['Avocado', 'Apple', 'mango', 'lemon']
Checking Items
You can check if an item exists using (in).
print('banana' in fruits) # True
print('lime' in fruits) # False
Adding Items
Lists grow dynamically with append() or insert().
fruits.append('lime')
fruits.insert(2, 'apple')
print(fruits)
Removing Items
Python provides several ways to remove items:
fruits.remove('banana')
fruits.pop() # removes last item
del fruits[0] # deletes by index
fruits.clear() # empties the list
Joining Lists
You can combine lists using + or extend().
fruits = ['banana', 'orange']
vegetables = ['Tomato', 'Carrot']
print(fruits + vegetables)
fruits.extend(vegetables)
print(fruits)
Counting, Indexing, and Sorting
Lists come with built‑in methods for analysis and organization.
print(fruits.count('orange'))
print(fruits.index('mango'))
fruits.sort()
print(fruits)
My take
Lists are versatile, dynamic, and essential for handling collections of data. They allow easy access, modification, slicing, and analysis, making them one of the most commonly used structures in Python.
Top comments (0)