Lists - Python Basics
Python Lists are one of the most important data structures you will use as a beginner in programming. Lists allow you to store multiple values in a single variable, making them extremely useful for organizing and manipulating data. In this educational guide, we will learn everything about lists step by step with examples, best practices, and tips for beginners.
What is a Python List?
A list in Python is a collection used to store multiple items in a single variable. Lists are:
- Ordered – Items have a defined order and will not change unless modified.
- Mutable – You can add, remove, or change items after the list is created.
- Allow duplicates – Lists can contain the same value multiple times.
- Heterogeneous – Lists can hold different data types (e.g., strings, numbers, booleans, even other lists).
# Example of a Python List
fruits = ["apple", "banana", "cherry"]
print(fruits)
# Output: ['apple', 'banana', 'cherry']
Characteristics of Python Lists
- Ordered – preserves insertion order.
- Mutable – supports item assignment, insertion, deletion.
- Indexed & Sliceable – supports positive/negative indexing and slicing.
- Dynamic – can grow or shrink at runtime.
- Heterogeneous – can mix data types.
Common Uses of Lists
- 📋 Group related data (e.g., names, scores, products).
- 🔄 Iterate and transform data with loops/comprehensions.
- 🧮 Temporary storage during calculations or parsing.
- 🧱 Build higher-level structures (queues, matrices as list of lists).
- 🛒 Real apps: shopping carts, playlists, todo lists, logs.
🔹 Access List Items
You can access list elements by their index number. Remember, Python indexing starts at 0.
# Syntax
item = my_list[index]
sublist = my_list[start:stop] # slicing
step_slice = my_list[start:stop:step] # with step
last_item = my_list[-1] # negative index from end
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: cherry (negative index counts from the end)
print(fruits[0:2]) # Output: ['apple', 'banana']
🔹 Change List Items
Lists are mutable, which means we can modify them after creation.
# Syntax
my_list[index] = new_value
my_list[start:end] = iterable # replace a slice with multiple values
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
🔹 Add List Items
There are three main ways to add items to a list:
# Syntax
my_list.append(x) # add at end
my_list.insert(i, x) # insert at index i
my_list.extend(iterable) # add many items
fruits = ["apple", "banana"]
# 1. Add item at the end
fruits.append("cherry")
# 2. Insert item at specific position
fruits.insert(1, "blueberry")
# 3. Add multiple items
fruits.extend(["orange", "grape"])
print(fruits)
# Output: ['apple', 'blueberry', 'banana', 'cherry', 'orange', 'grape']
🔹 Remove List Items
You can remove items from a list in different ways:
# Syntax
my_list.remove(x) # remove first occurrence of value x
my_list.pop(i) # remove and return item at index i (default last)
del my_list[i] # delete item at index i
my_list.clear() # remove all items
fruits = ["apple", "banana", "cherry", "orange"]
fruits.remove("banana") # Removes by value
fruits.pop(1) # Removes by index
del fruits[0] # Deletes a specific item
fruits.clear() # Clears the entire list
print(fruits) # Output: []
remove()
deletes only the first matching value. del
and clear()
permanently remove items—use carefully.
🔹 Loop Through a List
We can loop through a list using a for
loop or a while
loop.
# Syntax
for item in my_list:
...
for i, item in enumerate(my_list):
...
i = 0
while i < len(my_list):
...
i += 1
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
🔹 List Comprehension
List comprehension is a short and powerful way to create new lists from existing lists. It is useful when filtering or transforming items.
# Syntax
[expression for item in iterable if condition]
fruits = ["apple", "banana", "cherry", "kiwi"]
# Get fruits containing 'a'
newlist = [x for x in fruits if "a" in x]
print(newlist)
# Output: ['apple', 'banana']
🔹 Sort Lists
Lists can be sorted in ascending or descending order.
# Syntax
my_list.sort(key=None, reverse=False) # in-place
sorted_list = sorted(my_list, key=None, reverse=False) # returns new list
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 9]
numbers.sort(reverse=True)
print(numbers) # Output: [9, 5, 2, 1]
fruits = ["banana", "apple", "cherry"]
fruits.sort(key=len) # Sort by length of string
print(fruits) # Output: ['apple', 'banana', 'cherry']
🔹 Join Lists
Lists can be joined together using +
or extend()
.
# Syntax
combined = list1 + list2
list1.extend(list2)
merged = [*list1, *list2] # Python 3.5+ unpacking
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
# Method 1: Using +
combined = list1 + list2
print(combined)
# Method 2: Using extend()
list1.extend(list2)
print(list1)
🔹 Python List Methods (Complete Reference)
Method | Description |
---|---|
append() | Adds an item at the end |
insert() | Inserts item at a specific position |
extend() | Adds items from another iterable |
remove() | Removes the first matching value |
pop() | Removes item by index (returns it) |
clear() | Removes all items |
index() | Returns index of first matching value |
count() | Returns how many times an item appears |
sort() | Sorts list items in place |
reverse() | Reverses list order |
copy() | Returns a shallow copy of the list |
📝 Exercises
- Create a list of 5 numbers and print the sum and average.
- From a list of words, create a new list containing only words with length ≥ 5 (use list comprehension).
- Merge two lists and remove duplicates while keeping order.
- Sort a list of tuples
[("a",3),("b",1),("c",2)]
by the number usingkey
. - Given
nums=[1,2,3,4,5,6]
, buildodds
andevens
lists using comprehension.
❓ FAQs About Python Lists
Q1. Can lists store different data types?
Yes. A single list can hold ints, strings, floats, booleans, or even other lists.
Q2. What is the difference between remove()
and pop()
?remove(x)
deletes by value (first match). pop(i)
deletes by index and returns the item.
Q3. How do I copy a list safely?
Use my_list.copy()
or slicing my_list[:]
to avoid referencing the same list.
Q4. List vs Tuple?
Lists are mutable (changeable). Tuples are immutable (fixed). Tuples can be slightly faster and safer for fixed data.
✅ Conclusion
Python Lists are one of the most powerful tools in Python. They are flexible, easy to use, and form the foundation for many advanced concepts such as data analysis, machine learning, and handling user inputs.
0 Comments