Lists in Python

When learning Python, one of the most important data types you’ll encounter is the list.
Think of a lists in Python like a shopping bag — you can put multiple items inside it, take them out, add more, or even replace them.

Lists allow you to store multiple values in a single variable, and they are one of the most used data structures in Python.

Confused about how to store multiple URLs, so learning Lists in Python
Confused about how to store multiple URLs in Python

What is a List?

In Python, a list is a collection of items enclosed in square brackets [ ], separated by commas.

Example:

fruits = ["apple", "banana", "mango", "orange"]
print(fruits)

Output:

['apple', 'banana', 'mango', 'orange']

Here, fruits is a list that stores four fruit names.


Why Use Lists?

  • Store multiple values in one variable
  • Easily modify data (add, remove, change items)
  • Loop through data quickly
  • Great for tasks like shopping carts, student marks, to-do lists, etc.

List Basics

1. Creating a List

numbers = [10, 20, 30, 40]
print(numbers)

2. Accessing Elements (Indexing)

print(fruits[0])  # apple
print(fruits[-1]) # orange (last element)

3. Changing Elements

fruits[1] = "grapes"
print(fruits)  # ['apple', 'grapes', 'mango', 'orange']

Useful List Functions and Methods

Python provides many built-in methods to work with lists. Let’s see the most useful ones with examples:


1. append() – Add an item at the end

cart = ["milk", "bread"]
cart.append("eggs")
print(cart)

Output: ['milk', 'bread', 'eggs']


2. insert() – Insert item at specific position

cart.insert(1, "butter")
print(cart)

Output: ['milk', 'butter', 'bread', 'eggs']


3. remove() – Remove a specific item

cart.remove("bread")
print(cart)

Output: ['milk', 'butter', 'eggs']


4. pop() – Remove item by index (default last)

item = cart.pop()
print(item)   # eggs
print(cart)   # ['milk', 'butter']

5. sort() – Sort list (A to Z or ascending)

fruits = ["banana", "apple", "mango"]
fruits.sort()
print(fruits)

Output: ['apple', 'banana', 'mango']


6. reverse() – Reverse list order

numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers)

Output: [4, 3, 2, 1]


7. count() – Count occurrences

marks = [80, 90, 80, 70, 80]
print(marks.count(80))  # 3

8. index() – Find index of first occurrence

print(marks.index(70))  # 3

9. extend() – Add another list

cart = ["milk", "bread"]
extra = ["butter", "jam"]
cart.extend(extra)
print(cart)

Output: ['milk', 'bread', 'butter', 'jam']


10. len() – Get length of list

print(len(cart))  # 4

11. max() and min()

scores = [50, 90, 70, 100]
print(max(scores))  # 100
print(min(scores))  # 50

12. sum() – Total of numbers

print(sum(scores))  # 310

13. clear() – Empty the list

cart.clear()
print(cart)  # []

14. copy() – Copy a list

new_list = fruits.copy()
print(new_list)

Read More: Functions in Python


List Comprehensions

Sometimes we want to create a new list by applying some logic to an existing list. Instead of writing long for loops, Python gives us a short and clean way to do it — called List Comprehension.

Syntax:

new_list = [expression for item in iterable if condition]
  • expression → operation to perform
  • item → each element in the iterable (like a list or range)
  • condition (optional) → filter elements

Example 1: Squares of Numbers

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)

Output:

[1, 4, 9, 16, 25]

Example 2: Filtering Even Numbers

numbers = [10, 11, 12, 13, 14]
evens = [x for x in numbers if x % 2 == 0]
print(evens)

Output:

[10, 12, 14]

Real-Life Example: Extracting Valid Email IDs

emails = ["user@gmail.com", "test@", "hello@yahoo.com", "invalid"]
valid_emails = [email for email in emails if "@" in email and "." in email]
print(valid_emails)

Output:

['user@gmail.com', 'hello@yahoo.com']

Why use List Comprehension?

  • Saves time (less code to write)
  • Makes code clean and readable
  • Faster than traditional loops in many cases

Looping Through a List

You can use loops to go through each item:

for fruit in fruits:
    print(fruit)

Output:

apple
banana
mango

List Slicing in Python

List slicing allows you to get a portion of a list instead of the whole thing.
The syntax is:

list[start:end:step]
  • start → where slicing begins (index)
  • end → where slicing stops (but not included)
  • step → jump/skip between items

👉 Examples:

fruits = ["apple", "banana", "mango", "grapes", "orange", "kiwi"]

print(fruits[1:4])     # ['banana', 'mango', 'grapes']  
print(fruits[:3])      # ['apple', 'banana', 'mango']  
print(fruits[3:])      # ['grapes', 'orange', 'kiwi']  
print(fruits[::2])     # ['apple', 'mango', 'orange']  (every 2nd element)  
print(fruits[::-1])    # ['kiwi', 'orange', 'grapes', 'mango', 'banana', 'apple'] (reverse list)  

Real-life example:
Imagine you have daily stock prices in a list and you only want to check the last 5 days → you can use slicing:

stock_prices = [101, 103, 99, 105, 110, 115, 120]
print(stock_prices[-5:])   # [99, 105, 110, 115, 120]

Membership Operators in Lists (in and not in)

These operators check whether an item exists in a list or not.

👉 Examples:

fruits = ["apple", "banana", "mango", "grapes"]

print("apple" in fruits)      # True  
print("cherry" in fruits)     # False  
print("kiwi" not in fruits)   # True  

Real-life example:
Suppose you are creating a shopping cart system. Before adding an item, you can check if it already exists:

cart = ["milk", "bread", "butter"]

if "bread" in cart:
    print("Bread already in cart.")
else:
    cart.append("bread")
    
# or

if "bread" not in cart:
    cart.append("bread")
else:
    print("Bread already in cart.")

These two concepts make lists super powerful when dealing with real-world data like stock prices, student names, shopping items, or even URLs in automation scripts.


Real-Life Example: To-Do List

todo = []

todo.append("Complete homework")
todo.append("Go for walk")
todo.append("Read a book")

for task in todo:
    print("Task:", task)

Mini Practice Challenge for You

  1. Create a shopping cart program where users can:
    • Add items
    • Remove items
    • Show all items
  2. Write a program to store student marks and:
    • Show highest, lowest, and average marks
    • Count how many students scored above 80

Final Thoughts

Lists are one of the most important data structures in Python.
They’re flexible, easy to use, and super powerful when combined with loops and conditions.

Once you master lists, you’ll find that building programs like to-do apps, inventories, calculators, or even games becomes much easier.

Next, we’ll dive into Tuples and Sets in Python!

FAQs – Lists in Python

Yes, a list can hold mixed data types. For example:

data = [10, "hello", 3.14, True]

  • List: Can store mixed data types, flexible, built-in Python structure.

  • Array (from array module): Stores only one type of data (more memory efficient).

  • append() adds a single item to the list.

  • extend() adds multiple items from another list (or iterable).

a = [1, 2]
a.append([3, 4]) # [1, 2, [3, 4]]
a.extend([3, 4]) # [1, 2, 3, 4]

Use lists when:

  • You need to store multiple items in a single variable.

  • The order of items matters.

  • You may need to modify (add/remove/update) the collection.

What’s Next?

In the next post, we’ll learn about the Tuples in Python

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Translate »
Scroll to Top