Python Mastery – From Basics to Brilliance / Data Structures in Python

Lists

A list is an ordered, mutable (changeable) collection. Lists can contain different data types like numbers, strings, or even other lists.

fruits = ["apple", "banana", "cherry"]

πŸ” Why Use Lists?

  • To store multiple items in a single variable.

  • To maintain order (items have a specific index).

  • To easily add, remove, or modify items.


🧠 Indexing & Slicing

print(fruits[1])     # 2nd item
print(fruits[-1])    # Last item
print(fruits[1:3])   # Slice from 2nd to 3rd item

πŸ“Œ Common List Operations

fruits.append("orange")       # βž• Add to end
fruits.insert(1, "grape")     # βž• Add at specific index
fruits.remove("banana")       # ❌ Remove item by value
print(fruits[0])              # πŸ” Access first element
print(len(fruits))            # πŸ“ Get number of items
fruits.pop()                  # Removes last item
fruits.index("cherry")        # Finds index of an item
fruits.sort()                 # Sorts the list
fruits.reverse()              # Reverses the list order

πŸ” Loop Through a List

for fruit in fruits:
    print(fruit)
apple
grape
cherry
orange


πŸ§ͺ Example: Mixing Data Types

random_stuff = [42, "hello", 3.14, True]

Lists are flexible β€” you can store anything!


βœ… Summary

Feature

Description

Mutable

You can change it after creation

Indexed

Items have positions (0, 1, 2…)

Versatile

Can hold any data types

Dynamic

Grows/shrinks as needed