Python Lists
A list in Python is a built-in data structure used to store multiple values in a single variable. Lists are flexible, easy to use, and widely applied when working with collections of related data.
Creating a List
Lists are created using square brackets [], with items separated by commas.
items = ["pen", "notebook", "eraser"]
print(items)
What Is a List?
In Python, a list is one of the four core collection data types:
• List – Ordered, changeable, allows duplicate values
• Tuple – Ordered, unchangeable, allows duplicate values
• Set – Unordered, unindexed, no duplicate values
• Dictionary – Ordered, changeable, stores data as key–value pairs
Each collection type is designed for a different use case.
List Characteristics
1. Ordered
Lists maintain a fixed order. Items appear in the same sequence in which they were added.
colors = ["red", "green", "blue"]
print(colors)
New elements are always added at the end unless specified otherwise.
2. Changeable (Mutable)
Lists can be modified after creation—you can add, update, or remove elements.
numbers = [2, 4, 6]
numbers[1] = 10
print(numbers)
3. Allows Duplicate Values
Lists can store the same value multiple times because each item has a unique index.
names = ["John", "Emma", "John", "Alex"]
print(names)
Indexing in Lists
Each list item has a position called an index, starting from 0.
languages = ["Python", "Java", "C++"]
print(languages[0])
print(languages[2])
Finding the Length of a List
Use the len() function to determine how many elements a list contains.
cities = ["Delhi", "Mumbai", "Chennai"]
print(len(cities))
List Items and Data Types
A list can store elements of any data type.
Same Data Type Example
scores = [85, 90, 78, 92]
flags = [True, False, True]
Mixed Data Types Example
profile = ["Alex", 25, True, 5.8]
print(profile)
Checking the Data Type of a List
From Python’s perspective, lists are objects of type list.
data = ["car", "bike", "bus"]
print(type(data))
Output:
<class 'list'>
Creating a List Using the list() Constructor
You can also create a list using the list() constructor, especially when converting other iterable data types.
fruits = list(("mango", "orange", "grapes"))
print(fruits)
Note: Double parentheses are used because the inner one defines a tuple.
Python – Accessing List Items
In Python, list items are stored in an indexed sequence, which allows you to access specific elements by referring to their position. Indexing makes it easy to retrieve individual items or slices of data from a list.
Accessing Items by Index
Each item in a list has an index number, starting from 0.
fruits = ["mango", "orange", "grapes"]
print(fruits[1])
Explanation:
Index 1 refers to the second element in the list.
Python uses zero-based indexing.
Negative Indexing
Negative indexing allows access to list items from the end.
• -1 → last item
• -2 → second last item
fruits = ["mango", "orange", "grapes"]
print(fruits[-1])
Explanation:
This prints the last element of the list.
Accessing a Range of Items
You can retrieve multiple items at once using slicing.
items = ["pen", "pencil", "eraser", "scale", "marker", "sharpener"]
print(items[2:5])
Explanation:
• Starts from index 2 (included)
• Ends at index 5 (excluded)
• Returns a new list
Omitting the Start Index
If the starting index is omitted, Python begins from the first item.
items = ["pen", "pencil", "eraser", "scale", "marker"]
print(items[:3])
This returns all items from the beginning up to index 3 (not included).
Omitting the End Index
If the ending index is omitted, slicing continues until the end of the list.
items = ["pen", "pencil", "eraser", "scale", "marker"]
print(items[1:])
Range of Negative Indexes
You can also slice lists using negative index values.
items = ["pen", "pencil", "eraser", "scale", "marker", "sharpener"]
print(items[-4:-1])
• Starts from the fourth item from the end
• Stops before the last item
Checking if an Item Exists in a List
Use the in keyword to check whether a specific value exists in a list.
colors = ["red", "blue", "green"]
if "blue" in colors:
print("Yes, 'blue' is available in the list")
Explanation:
• The condition evaluates to True if the item is present.
• Commonly used in validation and conditional logic.
This rewritten section simplifies explanations, updates all examples, and maintains a clean tutorial flow.
Python – Changing List Items
Python lists are mutable, which means their contents can be modified after creation. You can update individual elements, replace multiple values at once, or insert new items at a specific position.
Changing a Single Item
To update a specific element in a list, access it using its index and assign a new value.
fruits = ["mango", "orange", "grapes"]
fruits[1] = "pineapple"
print(fruits)
Explanation:
• Index 1 refers to the second element.
• The old value is replaced with the new one.
Changing Multiple Items Using a Range
You can replace a group of items by assigning a new list to a slice.
fruits = ["mango", "orange", "grapes", "papaya", "apple"]
fruits[1:3] = ["kiwi", "strawberry"]
print(fruits)
Explanation:
Items at index 1 and 2 are replaced.
The number of replacement values matches the number of items removed.
Replacing with More Items Than Removed
If you insert more elements than you replace, the list size increases.
fruits = ["mango", "orange", "grapes"]
fruits[1:2] = ["kiwi", "strawberry"]
print(fruits)
Explanation:
One item is replaced with two new items.
The list length grows accordingly.
Replacing with Fewer Items Than Removed
If you insert fewer elements than you remove, the list size decreases.
fruits = ["mango", "orange", "grapes"]
fruits[1:3] = ["banana"]
print(fruits)
Explanation:
Two items are replaced with one.
The list becomes shorter.
Note: The length of the list changes whenever the number of inserted items differs from the number of replaced items.
Inserting Items Without Replacing Existing Ones
To add a new item at a specific position without removing any elements, use the insert() method.
fruits = ["mango", "orange", "grapes"]
fruits.insert(2, "apple")
print(fruits)
Explanation:
The new item is inserted at index 2.
Existing elements shift to the right.
This rewritten section provides clearer explanations and fresh examples while preserving the original concepts.
Python – Adding Items to a List
Python provides multiple ways to add new elements to a list. Depending on the requirement, you can add a single item, insert an item at a specific position, or merge another collection into an existing list.
Adding an Item Using append()
The append() method adds one element to the end of a list.
colors = ["red", "blue", "green"]
colors.append("yellow")
print(colors)
Explanation:
The new item is added after the last existing element.
The original list is modified directly.
Inserting an Item at a Specific Position
Use the insert() method to add an element at a chosen index.
colors = ["red", "blue", "green"]
colors.insert(1, "orange")
print(colors)
Explanation:
The new item is placed at index 1.
Existing elements shift to the right.
After using append() or insert(), the list size increases by one.
Extending a List with Another List
The extend() method allows you to add multiple items at once by appending elements from another list.
primary = ["pen", "pencil", "eraser"]
stationery = ["marker", "scale", "sharpener"]
primary.extend(stationery)
print(primary)
Explanation:
Each element from stationery is added individually.
Items are appended to the end of the list.
Adding Any Iterable to a List
The extend() method works with any iterable, not just lists—such as tuples, sets, or dictionaries.
tools = ["hammer", "screwdriver"]
extras = ("wrench", "pliers")
tools.extend(extras)
print(tools)
Explanation:
Elements from the tuple are added one by one.
The iterable’s structure is flattened into the list.
Key Differences
Method Adds Position
append() One item End of list
insert() One item Specific index
extend() Multiple items End of list
Python – Removing List Items
Python offers several ways to remove elements from a list, depending on whether you want to remove an item by value, by index, or clear the entire list.
Removing an Item by Value
The remove() method deletes the first occurrence of a specified value.
fruits = ["mango", "banana", "apple"]
fruits.remove("banana")
print(fruits)
Explanation:
The item "banana" is removed from the list.
If the value does not exist, Python raises an error.
Removing the First Matching Value
When a list contains duplicate values, remove() deletes only the first match.
fruits = ["mango", "banana", "apple", "banana", "kiwi"]
fruits.remove("banana")
print(fruits)
Explanation:
Only the first "banana" is removed.
Remaining duplicates stay in the list.
Removing an Item by Index Using pop()
The pop() method removes an element based on its index.
colors = ["red", "blue", "green"]
colors.pop(1)
print(colors)
Explanation:
Index 1 refers to the second element.
The removed item is returned if needed.
Removing the Last Item
If no index is specified, pop() removes the last element.
colors = ["red", "blue", "green"]
colors.pop()
print(colors)
Removing an Item Using del
The del keyword can remove an element at a specific index.
numbers = [10, 20, 30]
del numbers[0]
print(numbers)
Explanation:
The first element is removed.
del does not return the removed value.
Deleting an Entire List
The del keyword can also delete the entire list object.
items = ["pen", "pencil", "eraser"]
del items
After deletion, the list no longer exists and cannot be accessed.
Clearing All Items from a List
The clear() method removes all elements while keeping the list object intact.
tasks = ["email", "meeting", "report"]
tasks.clear()
print(tasks)
Explanation:
The list becomes empty.
The variable still exists and can be reused.
Python – Looping Through a List
Python provides several ways to iterate over list elements. You can loop directly through items, access elements by index, or use compact syntax like list comprehension.
Looping Through List Items Using a for Loop
The most common and readable way to loop through a list is with a for loop.
fruits = ["mango", "orange", "grapes"]
for item in fruits:
print(item)
Explanation:
Each element in the list is accessed one at a time.
This approach is simple and preferred when you don’t need index values.
Looping Using Index Numbers
If you need access to the index positions, you can loop using range() and len().
fruits = ["mango", "orange", "grapes"]
for index in range(len(fruits)):
print(f"Index {index}:", fruits[index])
Explanation:
len(fruits) gives the total number of items.
range() generates index values starting from 0.
Looping Through a List Using a while Loop
A while loop allows iteration using an index variable.
fruits = ["mango", "orange", "grapes"]
counter = 0
while counter < len(fruits):
print(fruits[counter])
counter += 1
Explanation:
The loop continues until the index reaches the list length.
The index must be incremented manually.
Looping with List Comprehension
List comprehension provides a compact way to loop through a list.
fruits = ["mango", "orange", "grapes"]
[print(item) for item in fruits]
Explanation:
This is a shorthand syntax.
Best used for short and simple operations.
When to Use Each Method
Method Best Use Case
for loop Simple iteration
for with index When index is required
while loop Condition-based iteration
This rewritten section improves readability, updates examples, and maintains a clear learning flow.
List Comprehension in Python
List comprehension is a concise and readable way to create a new list from an existing iterable. It reduces multiple lines of code into a single, expressive statement while keeping the logic clear.
Basic Idea
Suppose you have a list of items and you want
to build a new list based on certain rules or conditions. Traditionally, this requires a loop and conditional statements. List comprehension simplifies this process.
Example
You have a list of fruits and want to create a new list that contains only the fruits whose names include the letter “e”.
Traditional Approach (Without List Comprehension)
items = ["grape", "melon", "plum", "berry", "fig"]
filtered_items = []
for fruit in items:
if "e" in fruit:
filtered_items.append(fruit)
print(filtered_items)
Using List Comprehension (Recommended)
items = ["grape", "melon", "plum", "berry", "fig"]
filtered_items = [fruit for fruit in items if "e" in fruit]
print(filtered_items)
This single line replaces the loop, condition, and append operation.
General Syntax
new_list = [expression for element in iterable if condition]
• expression → What gets added to the new list
• element → Each item from the iterable
• iterable → A sequence like list, tuple, set, or range
• condition → Optional filter that must evaluate to True
The original iterable remains unchanged.
Using Conditions as Filters
Conditions help control which elements are included.
Example: Exclude a Specific Item
colors = ["red", "blue", "green", "red", "yellow"]
result = [c for c in colors if c != "red"]
print(result)
This keeps all values except "red".
Without Any Condition
If no filtering is needed, the condition part can be omitted.
numbers = [1, 2, 3, 4, 5]
copy_list = [n for n in numbers]
print(copy_list)
Working with Different Iterables
List comprehension works with any iterable object.
Example: Using range()
squares = [n * n for n in range(1, 6)]
print(squares)
With a Condition
even_numbers = [n for n in range(1, 11) if n % 2 == 0]
print(even_numbers)
Modifying Values Using Expressions
The expression part allows you to transform elements.
Example: Convert Strings to Uppercase
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names)
Example: Assign a Fixed Value
status = ["active" for _ in range(5)]
print(status)
Conditional Expressions Inside List Comprehension
You can also use inline conditions to change output values.
Example: Replace a Specific Value
fruits = ["apple", "banana", "cherry"]
updated_fruits = [fruit if fruit != "banana" else "orange" for fruit in fruits]
print(updated_fruits)
Here, "banana" is replaced with "orange" while other values remain unchanged.
Case-Insensitive Sorting in Python Lists
By default, Python sorts strings case-sensitively. This means all uppercase letters are placed before lowercase letters based on their ASCII values, which can sometimes lead to confusing results.
Default Case-Sensitive Sort
Consider the following example:
items = ["grapes", "Apple", "mango", "Cherry"]
items.sort()
print(items)
Output (case-sensitive):
Uppercase words appear first, followed by lowercase ones.
Case-Insensitive Sorting Using a Key Function
To sort strings without considering letter case, Python allows the use of key functions. A key function transforms each element before comparison.
Using str.lower ensures all values are compared in lowercase form.
items = ["grapes", "Apple", "mango", "Cherry"]
items.sort(key=str.lower)
print(items)
This produces a more natural alphabetical order, regardless of capitalization.
Sorting in Reverse Order
Sometimes you may want to reverse the order of elements in a list, independent of alphabetical rules.
Reversing a List
The reverse() method simply flips the current order of elements in the list.
items = ["grapes", "Apple", "mango", "Cherry"]
items.reverse()
print(items)
Tip
If you want to sort and reverse at the same time, Python also supports:
items.sort(key=str.lower, reverse=True)
print(items)
Copying a List in Python
In Python, assigning one list to another using = does not create a new list. Instead, both variables point to the same list object. As a result, changes made to one list will affect the other.
Why Direct Assignment Is a Problem
list_a = ["pen", "pencil", "eraser"]
list_b = list_a
list_a.append("marker")
print(list_b)
Here, list_b reflects the change because it references the same list as list_a.
Correct Ways to Copy a List
To create an independent copy, you can use one of the following methods.
1. Using the copy() Method
The copy() method creates a shallow copy of the list.
original = ["pen", "pencil", "eraser"]
duplicate = original.copy()
print(duplicate)
Any changes to original will not affect duplicate.
2. Using the list() Constructor
The built-in list() function can also be used to create a new list from an existing one.
original = ["pen", "pencil", "eraser"]
duplicate = list(original)
print(duplicate)
This approach works the same way as copy().
3. Using the Slice Operator (:)
Slicing the entire list creates a new list with the same elements.
original = ["pen", "pencil", "eraser"]
duplicate = original[:]
print(duplicate)
Joining (Concatenating) Lists in Python
In Python, you can combine two or more lists in multiple ways. The method you choose depends on whether you want to create a new list or modify an existing list.
1. Using the + Operator
The + operator joins lists and returns a new list, leaving the original lists unchanged.
letters = ["x", "y", "z"]
numbers = [10, 20, 30]
combined = letters + numbers
print(combined)
✔ Best when you want a new list without altering the originals.
2. Appending Elements One by One
You can also add elements from one list to another using a loop and the append() method.
letters = ["x", "y", "z"]
numbers = [10, 20, 30]
for value in numbers:
letters.append(value)
print(letters)
✔ Useful when you need more control during the insertion process.
3. Using the extend() Method
The extend() method adds all elements from one list to the end of another list in a single step.
letters = ["x", "y", "z"]
numbers = [10, 20, 30]
letters.extend(numbers)
print(letters)