Lists in Python are a fundamental data structure for storing and manipulating collections of items. This article explains what lists are, their properties, and how to use them effectively in Python. It also explores common list operations, methods, and practical applications to help you understand lists thoroughly.
Contents:
- Introduction to Python Lists
- Creating a Lists in Python
- Accessing Elements in a List in Python
- Modifying and Updating Lists in Python
- Adding Elements to a List in Python
- Removing Elements from a List in Python
- List Slicing in Python
- Iterating Through a List in Python
- List Comprehensions in Python
- Nested Lists in Python
- Common List Methods and Functions in Python
- Sorting and Reversing Lists in Python
- Copying Lists in Python
- FAQs on Python Lists
Introduction to Python Lists
A list in Python is an ordered, mutable, and dynamic collection that can store multiple items in a single variable. Lists can contain elements of different data types, such as integers, strings, floats, or even other lists.
Key Features of Lists:
- Ordered: Elements are stored in a defined order.
- Mutable: Lists can be modified (add, remove, or change elements).
- Heterogeneous: Can store different data types in a single list.
Creating a Lists in Python
In Python, you can create a list using square brackets [], separating elements with commas. A list can hold different types of data, like numbers, words, decimals, or even other lists.
1. Creating an Empty List
# Empty list sanfoundry_list = [] print(sanfoundry_list)
Output:
[]
2. Creating a List with Elements
# List of subjects subjects = ["Python", "Java", "DBMS", "AI"] print(subjects) # List with different data types data = [101, "Sanfoundry", 3.14, True] print(data)
Output:
['Python', 'Java', 'DBMS', 'AI'] [101, 'Sanfoundry', 3.14, True]
3. Creating a List Using list() Constructor
# Using list() constructor quiz_list = list(("Python", "Java", "C++")) print(quiz_list)
Output:
['Python', 'Java', 'C++']
4. Creating a List with Repeated Elements
# List with repeated elements repeat_list = ["AI"] * 4 print(repeat_list)
Output:
['AI', 'AI', 'AI', 'AI']
5. Creating a Nested List
# Nested list with different types of elements nested_list = ["ML", [101, "DBMS"], [3.14, "AI"]] print(nested_list)
Output:
['ML', [101, 'DBMS'], [3.14, 'AI']]
6. Creating a List Using List Comprehension
squares = [x**2 for x in range(5)] print(squares)
Output:
[0, 1, 4, 9, 16]
7. Creating a List from a String
# Convert string to list text = "Sanfoundry" char_list = list(text) print(char_list)
Output:
['S', 'a', 'n', 'f', 'o', 'u', 'n', 'd', 'r', 'y']
Accessing Elements in a List in Python
You can access elements in a Python list using indexing, negative indexing, slicing, and looping.
1. Accessing Elements Using Indexing
Python lists are zero-indexed, meaning the first element is at index 0.
# Sanfoundry Subjects List subjects = ["Python", "Java", "DBMS", "AI", "ML"] # Access first element print(subjects[0]) # Access third element print(subjects[2]) # Access last element using negative index print(subjects[-1])
Output:
Python DBMS ML
2. Accessing a Range of Elements Using Slicing
Slicing allows extracting a portion of the list.
Example:
# Sanfoundry Subjects List subjects = ["Python", "Java", "DBMS", "AI", "ML"] # Slicing elements from index 1 to 3 print(subjects[1:4]) # Access first three elements print(subjects[:3]) # Access elements from index 2 to end print(subjects[2:])
Output:
['Java', 'DBMS', 'AI'] ['Python', 'Java', 'DBMS'] ['DBMS', 'AI', 'ML']
3. Accessing Elements in Nested Lists
# Nested List nested_list = ["Python", ["DBMS", "Java"], "AI"] # Access "Java" from the nested list print(nested_list[1][1])
Output:
Java
Modifying and Updating Lists in Python
Modifying Elements by Index
subjects = ["Python", "Java", "DBMS", "AI"] subjects[1] = "C++" print(subjects)
Output:
['Python', 'C++', 'DBMS', 'AI']
You can also modify multiple elements at once:
# Initial list subjects = ["Python", "Java", "DBMS", "AI"] # Modify multiple elements subjects[1:3] = ["C++", "Data Science"] print(subjects)
Output:
['Python', 'C++', 'Data Science', 'AI']
Adding Elements to a List in Python
There are multiple ways to add elements to a list:
Using append() (Adds a single element to the end)
subjects = ["Python", "Java", "DBMS", "AI"] # Add at the end subjects.append("ML") print(subjects) # Output: ['Python', 'Java', 'DBMS', 'AI', 'ML']
Using insert() (Adds an element at a specific index)
subjects = ["Python", "Java", "DBMS", "AI"] subjects.insert(2, "Data Science") print(subjects) # Output: ['Python', 'Java', 'Data Science', 'DBMS', 'AI']
Using extend() (Adds multiple elements from another list)
subjects = ["Python", "Java", "DBMS", "AI"] subjects.extend(["IoT", "Cybersecurity"]) print(subjects) # Output: ['Python', 'Java', 'DBMS', 'AI', 'IoT', 'Cybersecurity']
Removing Elements from a List in Python
You can remove elements from a list using various methods:
1. Using remove()
Removes the first occurrence of a specified element.
subjects = ["Python", "Java", "DBMS", "AI", "Java"] subjects.remove("Java") print(subjects)
Output:
['Python', 'DBMS', 'AI', 'Java']
2. Using pop()
Removes an element by index. If no index is specified, removes the last element.
subjects = ["Python", "Java", "DBMS", "AI", "Java"] # Remove element at index 2 subjects.pop(2) print(subjects) # Remove last element subjects.pop() print(subjects)
Output:
['Python', 'Java', 'AI', 'Java'] ['Python', 'Java', 'AI']
3. Using del Statement
Deletes an element by index or a range of elements.
subjects = ["Python", "Java", "DBMS", "AI", "Java"] # Delete element at index 1 del subjects[1] print(subjects)
Output:
['Python', 'DBMS', 'AI', 'Java']
Delete a range of elements in List
subjects = ["Python", "Java", "DBMS", "AI", "Java"] del subjects[1:4] print(subjects)
Output:
['Python', 'Java']
4. Using clear()
Removes all elements from the list.
subjects = ["Python", "Java", "DBMS", "AI", "Java"] subjects.clear() print(subjects)
Output:
[]
List Slicing in Python
Slicing allows you to access a subset of elements from a list. The syntax is:
list[start:stop:step]
- start → The starting index (inclusive).
- stop → The ending index (exclusive).
- step → The step size (optional, default is 1).
1. Basic Slicing
subjects = ["Python", "Java", "DBMS", "AI", "ML", "C++"] # Slice elements from index 1 to 4 print(subjects[1:4])
Output:
['Java', 'DBMS', 'AI']
2. Slicing with Default Values
subjects = ["Python", "Java", "DBMS", "AI", "ML", "C++"] # Slice from start to index 3 print(subjects[:3]) # ['Python', 'Java', 'DBMS'] # Slice from index 2 to end print(subjects[2:]) # ['DBMS', 'AI', 'ML', 'C++'] # Copy entire list print(subjects[:]) # ['Python', 'Java', 'DBMS', 'AI', 'ML', 'C++']
3. Slicing with Step
subjects = ["Python", "Java", "DBMS", "AI", "ML", "C++"] # Every second element print(subjects[::2]) # ['Python', 'DBMS', 'ML'] # Reverse list print(subjects[::-1]) # ['C++', 'ML', 'AI', 'DBMS', 'Java', 'Python']
Iterating Through a List in Python
You can iterate through a list using different methods like for loops, while loops, and list comprehensions.
1. Using a for Loop
# List of subjects subjects = ["Python", "Java", "DBMS", "AI"] # Using for loop to iterate for sub in subjects: print(sub)
Output:
Python Java DBMS AI
2. Using for Loop with range() and Indexing
# List of subjects subjects = ["Python", "Java", "DBMS", "AI"] # Using for loop with range and indexing for i in range(len(subjects)): print(subjects[i])
Output:
Python Java DBMS AI
3. Using while Loop
# List of subjects subjects = ["Python", "Java", "DBMS", "AI"] # Using while loop to iterate i = 0 while i < len(subjects): print(subjects[i]) i += 1
Output:
Python Java DBMS AI
4. Using List Comprehension
# List of subjects subjects = ["Python", "Java", "DBMS", "AI"] # Using list comprehension [print(sub) for sub in subjects]
Output:
Python Java DBMS AI
5. Using enumerate() to Get Index and Value
# List of subjects subjects = ["Python", "Java", "DBMS", "AI"] # Using enumerate() to iterate with index and value for i, sub in enumerate(subjects): print(f"{i}: {sub}")
Output:
0: Python 1: Java 2: DBMS 3: AI
List Comprehensions in Python
List comprehensions provide a concise way to create lists using a single line of code. The syntax is:
[expression for item in iterable if condition]
1. Basic List Comprehension
# Create a list of squares squares = [x**2 for x in range(5)] print(squares)
Output:
[0, 1, 4, 9, 16]
2. List Comprehension with if Condition
# Filter even numbers even_numbers = [x for x in range(10) if x % 2 == 0] print(even_numbers)
Output:
[0, 2, 4, 6, 8]
3. List Comprehension with if-else
# Categorize numbers as even or odd number_type = ["Even" if x % 2 == 0 else "Odd" for x in range(5)] print(number_type)
Output:
['Even', 'Odd', 'Even', 'Odd', 'Even']
4. Nested List Comprehension
# Create a 2D list using nested list comprehension matrix = [[j for j in range(3)] for i in range(2)] print(matrix)
Output:
[[0, 1, 2], [0, 1, 2]]
5. List Comprehension with enumerate()
# Create list of subject names with their indexes subjects = ["Python", "Java", "DBMS", "AI"] indexed_subjects = [f"{i}: {sub}" for i, sub in enumerate(subjects)] print(indexed_subjects)
Output:
['0: Python', '1: Java', '2: DBMS', '3: AI']
Nested Lists in Python
A nested list is a list inside another list. It allows storing multiple dimensions of data, such as matrices.
1. Creating a Nested List
# 2D list representing student scores scores = [[85, 90, 88], [78, 81, 86], [92, 95, 89]] print(scores)
Output:
[[85, 90, 88], [78, 81, 86], [92, 95, 89]]
2. Accessing Elements in a Nested List
scores = [[85, 90, 88], [78, 81, 86], [92, 95, 89]] # Accessing specific elements print(scores[0]) # First row print(scores[1][2]) # Third element in second row
Output:
[85, 90, 88] 86
3. Iterating Through a Nested List
scores = [[85, 90, 88], [78, 81, 86], [92, 95, 89]] # Print all elements using a nested loop for row in scores: for value in row: print(value, end=" ") print()
Output:
85 90 88 78 81 86 92 95 89
Common List Methods and Functions in Python
Python provides several built-in methods and functions to manipulate and work with lists efficiently. Here are the commonly used list methods and functions:
| Method | Description | Example |
|---|---|---|
| append(x) | Adds an element x to the end of the list | lst.append(10) |
| insert(i, x) | Inserts x at index i | lst.insert(2, 20) |
| extend(iter) | Adds multiple elements from an iterable | lst.extend([30, 40]) |
| remove(x) | Removes the first occurrence of x | lst.remove(10) |
| pop(i) | Removes and returns element at index i (default last) | lst.pop(1) |
| clear() | Removes all elements from the list | lst.clear() |
| index(x) | Returns the index of the first occurrence of x | lst.index(20) |
| count(x) | Counts the occurrences of x in the list | lst.count(30) |
| sort() | Sorts the list in ascending order | lst.sort() |
| reverse() | Reverses the order of elements | lst.reverse() |
| copy() | Returns a shallow copy of the list | new_lst = lst.copy() |
Sorting and Reversing Lists in Python
1. Sorting a List Using sort()
sort() sorts the list in-place in ascending order.
# List of marks marks = [78, 92, 65, 89, 74] # Sort in ascending order marks.sort() print(marks)
Output:
[65, 74, 78, 89, 92]
2. Sorting in Descending Order
Use reverse=True with sort() to sort in descending order.
# List of marks marks = [78, 92, 65, 89, 74] # Sort in descending order marks.sort(reverse=True) print(marks)
Output:
[92, 89, 78, 74, 65]
3. Using sorted() to Create a New Sorted List
sorted() returns a new list without modifying the original list.
# Original list of subjects subjects = ["Python", "Java", "DBMS", "AI"] # Create a sorted list sorted_subjects = sorted(subjects) print(sorted_subjects) print(subjects) # Original list remains unchanged
Output:
['AI', 'DBMS', 'Java', 'Python'] ['Python', 'Java', 'DBMS', 'AI']
4. Reversing a List Using reverse()
reverse() reverses the list in-place.
subjects = ["Python", "Java", "DBMS", "AI"] # Reverse the list subjects.reverse() print(subjects)
Output:
['AI', 'DBMS', 'Java', 'Python']
5. Using reversed() to Create a New Reversed List
reversed() returns a new reversed iterator.
subjects = ["Python", "Java", "DBMS", "AI"] # Create a reversed list reversed_subjects = list(reversed(subjects)) print(reversed_subjects)
Output:
['Python', 'Java', 'DBMS', 'AI']
Copying Lists in Python
Copying a list creates a new list that stores the same elements as the original list. There are different ways to copy lists in Python.
1. Using copy() Method
The copy() method returns a shallow copy of the list.
# Original list subjects = ["Python", "Java", "DBMS", "AI"] # Copy the list copy_subjects = subjects.copy() print(copy_subjects)
Output:
['Python', 'Java', 'DBMS', 'AI']
2. Using Slicing [:]
Slicing with [:] creates a copy of the entire list.
subjects = ["Python", "Java", "DBMS", "AI"] # Copy using slicing copy_subjects = subjects[:] print(copy_subjects)
Output:
['Python', 'Java', 'DBMS', 'AI']
3. Using list() Constructor
The list() constructor converts any iterable (like another list) into a new list.
subjects = ["Python", "Java", "DBMS", "AI"] # Copy using list() constructor copy_subjects = list(subjects) print(copy_subjects)
Output:
['Python', 'Java', 'DBMS', 'AI']
4. Using deepcopy() for Nested Lists
Use copy.deepcopy() to create a deep copy of a nested list.
import copy # Nested list nested_subjects = [["Python", "Java"], ["DBMS", "AI"]] # Deep copy of nested list deep_copy_subjects = copy.deepcopy(nested_subjects) print(deep_copy_subjects)
Output:
[['Python', 'Java'], ['DBMS', 'AI']]
FAQs on Python Lists
1. What is a list in Python?
A list is an ordered, mutable collection of items that can store multiple data types, such as numbers, strings, and other lists.
2. How do you create a list?
Lists are created using square brackets [], with elements separated by commas.
3. How do you access elements in a list?
Elements are accessed using their index, starting from 0 for the first element. Negative indexing allows access from the end of the list.
4. How do you add elements to a list?
You can add elements using methods like append() to add at the end, insert() to add at a specific position, and extend() to add multiple elements.
5. How do you remove elements from a list?
Elements can be removed using remove() (by value), pop() (by index), or clear() (to remove all elements).
6. How do you find the length of a list?
The number of elements in a list can be found using the len() function.
7. How do you copy a list?
Lists can be copied using the copy() method or slicing. Assigning a list to another variable without copying creates a reference.
8. What are list comprehensions?
List comprehensions provide a compact way to create lists using a single line of code, often used for transforming or filtering data.
Key Points to Remember
Here is the list of key points we need to remember about “Python Lists”.
- Python lists are ordered, mutable collections that can store multiple data types, including integers, strings, and other lists.
- Lists are created using square brackets [] or the list() constructor, e.g., my_list = [1, 2, 3].
- Elements are accessed using indexing (list[0] for the first element) and slicing (list[start:end] to extract sublists).
- Lists can be modified using methods like append(), insert(), remove(), and pop(), or by directly updating values via indexing.
- Iteration is done using for and while loops, with enumerate() providing both index and value.
- Common list methods include sort(), reverse(), count(), extend(), and copy(), which help with various operations.
- List comprehension, such as [x**2 for x in range(5)], offers an efficient way to create and manipulate lists.