DEV Community

Cover image for Creating Lists
Mary Nyandia
Mary Nyandia

Posted on

Creating Lists

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))

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Checking Items
You can check if an item exists using (in).

print('banana' in fruits)  # True
print('lime' in fruits)    # False

Enter fullscreen mode Exit fullscreen mode

Adding Items
Lists grow dynamically with append() or insert().

fruits.append('lime')
fruits.insert(2, 'apple')
print(fruits)

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Joining Lists
You can combine lists using + or extend().

fruits = ['banana', 'orange']
vegetables = ['Tomato', 'Carrot']
print(fruits + vegetables)

fruits.extend(vegetables)
print(fruits)

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)