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.
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.
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.
3. Allows Duplicate Values
Lists can store the same value multiple times because each item has a unique index.
Indexing in Lists
Each list item has a position called an index, starting from 0.
Finding the Length of a List
Use the len() function to determine how many elements a list contains.
List Items and Data Types
A list can store elements of any data type.
Same Data Type Example
Mixed Data Types Example
Checking the Data Type of a List
From Python’s perspective, lists are objects of type list.
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.
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.
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
Explanation:
This prints the last element of the list.
Accessing a Range of Items
You can retrieve multiple items at once using slicing.
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.
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.
Range of Negative Indexes
You can also slice lists using negative index values.
• 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.
Explanation:
• The condition evaluates to True if the item is present.
• Commonly used in validation and conditional logic.
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.
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.
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.
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.
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.
Explanation:
The new item is inserted at index 2.
Existing elements shift to the right.
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.
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.
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.
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.
Explanation:
Elements from the tuple are added one by one.
The iterable’s structure is flattened into the 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.
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.
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.
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.
Removing an Item Using del
The del keyword can remove an element at a specific index.
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.
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.
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.
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().
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.
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.
Explanation:
This is a shorthand syntax.
Best used for short and simple operations.
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.
Traditional Approach (Without List Comprehension)
Using List Comprehension (Recommended)
This single line replaces the loop, condition, and append operation.
Using Conditions as Filters
Example: Exclude a Specific Item
This keeps all values except "red".
Without Any Condition
Working with Different Iterables
Example: Using range()
With a Condition
Modifying Values Using Expressions
Example: Convert Strings to Uppercase
Example: Assign a Fixed Value
Conditional Expressions Inside List Comprehension
Example: Replace a Specific Value
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
Output (case-sensitive):
Uppercase words appear first, followed by lowercase ones.
Case-Insensitive Sorting Using a Key Function
This produces a more natural alphabetical order, regardless of capitalization.
Reversing a List
Tip
If you want to sort and reverse at the same time, Python also supports:
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
Here, list_b reflects the change because it references the same list as list_a.
Correct Ways to Copy a List
1. Using the copy() Method
2. Using the list() Constructor
3. Using the Slice Operator (:)
Joining (Concatenating) Lists in Python
1. Using the + Operator
✔ Best when you want a new list without altering the originals.
