Python Lists Exercises
Python Lists Practice Questions
Which of the following statements about Python lists is correct?
Python lists are a versatile data structure that allow you to store multiple items in a single variable. Here’s what makes lists special:
- Heterogeneous elements: Lists can store elements of different data types, e.g., integers, strings, floats, and even other lists.
- Mutable: Unlike strings or tuples, you can modify a list after it is created by adding, removing, or changing elements.
- Ordered: The elements in a list maintain the order in which they were added, allowing access by index.
Example:
my_list = [10, "hello", 3.14, True]
print(my_list[1]) # Output: hello
Key Takeaways:
- Use lists when you need a collection of items that can change over time.
- You can mix different data types in the same list.
- Remember: Lists are ordered, mutable, and versatile.
What will be the content of my_list after executing the following code?
my_list = [1, 2, 3]
my_list.append(4)
In Python, the append() method adds a single element to the end of a list.
- The original list is
[1, 2, 3]. my_list.append(4)adds the element4at the end of the list.- The updated list becomes
[1, 2, 3, 4].
Key Points:
append()always adds a single item to the end.- If you want to add multiple elements, use
extend()instead. - Remember,
append()modifies the list in place; it does not return a new list.
Which of the following methods can be used to insert an element at a specific position in a Python list?
Python provides several methods to modify lists. To insert an element at a specific index, you can use the insert() method.
- Syntax:
list.insert(index, element) - Example:
my_list = [10, 20, 30]
my_list.insert(1, 15) # Insert 15 at index 1
print(my_list) # Output: [10, 15, 20, 30]
append()adds at the end.extend()adds multiple elements from another iterable.remove()deletes an element.
Tip: Use insert() when you need precise placement of an element in the list.
What will be the result of the following slicing operation?
my_list = [10, 20, 30, 40, 50]
print(my_list[1:4])
Python list slicing allows you to extract a portion of the list using the syntax list[start:end]. The start index is inclusive, and the end index is exclusive.
- Here,
my_list[1:4]starts at index 1 (value 20) and goes up to, but not including, index 4 (value 50). - So the sliced list is
[20, 30, 40].
Key Takeaways:
- Remember: slicing does not modify the original list.
- Negative indices can be used to slice from the end.
- Omitting start or end defaults to the beginning or end of the list.
Which of the following methods can be used to find the number of elements in a Python list?
To find the number of elements in a Python list, we use the built-in len() function. This function works for lists, strings, tuples, dictionaries, and other iterable objects.
- Example:
my_list = [5, 10, 15, 20]
print(len(my_list)) # Output: 4
length()andsize()are not valid Python functions for lists.count()counts how many times a specific element appears in the list, not the total number of elements.
Tip: Use len() whenever you need the size of a list. It’s fast, simple, and built-in.
Which of the following statements about iterating through Python lists is correct?
Python lists are iterable objects, meaning you can loop through their elements in multiple ways.
- For loops: The most common way to iterate through a list.
- While loops: Can also be used by manually managing an index.
- Enumerate: Provides both the index and value while iterating.
Examples:
# Using for loop
my_list = [10, 20, 30]
for item in my_list:
print(item)
# Using while loop
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
# Using enumerate
for index, value in enumerate(my_list):
print(index, value)
Key Takeaways:
- Lists are iterable, so for loops are simple and readable.
- While loops give you more control over indices.
- Use
enumerate()when you need the index alongside the value.
What will be the output of the following code?
The remove() method removes the first occurrence of the specified element from the list.
- Original list:
[5, 10, 15, 20] my_list.remove(10)removes the value10from the list.- The resulting list is
[5, 15, 20].
Key Points:
remove()only removes the first matching element.- If the element is not found, Python raises a
ValueError. - To remove by index, use
pop(index)instead.
Which of the following expressions checks if the value 50 exists in the list my_list?
In Python, the in operator is used to check whether an element exists in a list.
- It returns
Trueif the element is present,Falseotherwise. - Example:
my_list = [10, 20, 30, 50]
print(50 in my_list) # Output: True
print(100 in my_list) # Output: False
- Methods like
has()orcontains()do not exist for Python lists. - Accessing
my_list[50]will try to access the element at index 50, which may raise anIndexError.
Tip: Use the in operator for simple and readable membership checks.
Which of the following operations combines two lists list1 and list2 into a single list?
There are multiple ways to combine lists in Python, but using the + operator concatenates them into a new list.
list1 + list2returns a new list containing all elements from both lists.- Example:
list1 = [1, 2, 3]
list2 = [4, 5]
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4, 5]
append()adds the entire list as a single element, e.g.,[1, 2, 3, [4, 5]].remove()deletes a specific element.pop()removes an element by index.
Tip: Use + for combining lists into a new list, or extend() to add elements in place.
What will be the content of my_list after executing the following code?
my_list = [10, 20, 30, 40]
del my_list[1]
The del statement in Python is used to delete an element at a specific index from a list.
- Original list:
[10, 20, 30, 40] del my_list[1]removes the element at index 1 (value 20).- Resulting list:
[10, 30, 40]
Key Points:
pop(index)also removes an element but returns it.del list[index]removes the element without returning it.- Using
delwith slicing can remove multiple elements at once, e.g.,del my_list[1:3].
Which of the following statements about nested lists in Python is correct?
Nested lists are lists that contain other lists as elements. They allow creating multi-dimensional data structures, like matrices.
- You can access elements in a nested list using multiple indices. The first index selects the sublist, and the second index selects the element within that sublist.
- Example conceptual understanding:
- Consider a nested list representing a 2x2 matrix:
[[1, 2], [3, 4]] - Access element
4: first select the second sublist, then the second element →matrix[1][1]
- Consider a nested list representing a 2x2 matrix:
Key Points:
- Nested lists can contain lists of any length and any data type.
- They are mutable, so elements within can be modified.
- Multiple indexing allows precise access to deeply nested elements.
What will be the output of the following code?
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix[1][0] = matrix[2][2]
matrix[2] = [0, 0, 0]
print(matrix[1][0], matrix[2][2])
This question tests your understanding of **nested list references** and assignment in Python.
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix = [[1, 2, 3],
[9, 5, 6],
[0, 0, 0]]
- Original
matrix: matrix[1][0] = matrix[2][2]sets the element at row 1, column 0 to the value ofmatrix[2][2], which is 9.matrix[2] = [0, 0, 0]replaces the entire third row with zeros.- Now:
- So
matrix[1][0]is 9 andmatrix[2][2]is 0.
Key Takeaways:
- Assignment to individual elements copies the value, not the reference.
- Assigning a new list to
matrix[2]replaces the entire sublist. - Nested list operations require careful tracking of indices and assignments.
Which of the following methods sorts the list numbers in descending order?
Sorting lists in Python can be done using either the sort() method or the sorted() function.
numbers.sort()sorts the list in place in ascending order by default.sorted(numbers)returns a new sorted list in ascending order without modifying the original.numbers.reverse()simply reverses the current order of elements without sorting.numbers.sort(reverse=True)sorts the list in place in descending order.
Example:
numbers = [5, 2, 9, 1]
numbers.sort(reverse=True)
print(numbers) # Output: [9, 5, 2, 1]
Tips:
- Use
sort(reverse=True)for descending sort in place. - Use
sorted()if you need a new sorted list and want to keep the original unchanged. - Remember,
reverse()does not sort; it just reverses the current order.
Which of the following code snippets creates a new list containing the sum of elements from list1 and list2 at the same indices?
This question tests **index-based operations on multiple lists** and understanding list comprehensions.
- We want to sum elements at the same indices from two lists.
Option 3correctly uses a list comprehension with index iteration:[list1[i] + list2[i] for i in range(len(list1))]Option 1multiplies elements instead of adding.Option 2subtracts elements.Option 4concatenates the lists rather than summing element-wise.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = [list1[i] + list2[i] for i in range(len(list1))]
print(result) # Output: [5, 7, 9]
Key Takeaways:
- Use list comprehensions for concise element-wise operations.
- Ensure both lists have the same length when using index-based operations.
- Remember:
+on lists concatenates, it doesn’t sum elements element-wise.
Which of the following code snippets correctly calculates the sum of all elements in the list numbers?
To calculate the sum of all elements in a Python list, the built-in sum() function is the simplest and most efficient method.
- Option 1: Correct –
total = sum(numbers)sums all elements in the list. - Option 2 –
add()does not exist for lists. - Option 3 – multiplies elements instead of adding.
- Option 4 – uses
reducewith subtraction, which is incorrect for summing.
Example:
numbers = [1, 2, 3, 4]
total = sum(numbers)
print(total) # Output: 10
Tips:
- Use
sum()for simple and readable code. - For advanced aggregations,
reduce()can be used, but ensure the operation is correct.
Which of the following statements about list references and mutability in Python is correct?
This question tests your understanding of **how Python handles list references and mutability**.
- Lists are **mutable**, meaning their elements can be changed.
- When you assign one list to another, e.g.,
list2 = list1, both variables reference the **same list object** in memory. - Therefore, modifying the list through one variable will affect the other.
Example:
list1 = [1, 2, 3]
list2 = list1
list2.append(4)
print(list1) # Output: [1, 2, 3, 4]
print(list2) # Output: [1, 2, 3, 4]
Key Takeaways:
- Option 3 – Correct: Both variables point to the same list, so changes are reflected in both.
- Use
list.copy()orcopy.deepcopy()to create independent copies. - Remember: Python variables hold references to objects, not the objects themselves.
What will be the output of the following code?
a = [1, 2, 3]
b = a
b[0] = 100
print(a)
This question tests your understanding of **list references and mutability** in Python.
- Variable
areferences a list[1, 2, 3]. - When we assign
b = a, bothaandbreference the **same list object**. - Modifying
b[0] = 100changes the first element of the shared list. - Therefore, printing
aalso shows the updated list.
Key Takeaways:
- Option 2 – Correct: The first element is updated to 100 in both
aandb. - To avoid modifying the original list, use
b = a.copy()to create a shallow copy. - Remember: Python variables store references, not independent copies.
Which of the following code snippets correctly flattens a nested list nested_list = [1, [2, [3, 4], 5], 6] into a single-level list?
This question tests **recursion and nested list handling** in Python.
- Option 3 – Correct: Uses a recursive function to flatten nested lists of any depth.
- It checks if an element is a list. If yes, it recursively flattens it using
extend(); otherwise, it appends the element. - Other options fail:
- Option 1 just appends sublists as-is.
- Option 2 still keeps nested lists inside.
- Option 4 only iterates over the top-level elements without flattening.
Example output:
nested_list = [1, [2, [3, 4], 5], 6]
flat_list = flatten(nested_list)
print(flat_list) # Output: [1, 2, 3, 4, 5, 6]
Key Takeaways:
- Recursion is powerful for handling nested structures.
- Use
isinstance()to check types safely. extend()is crucial to merge lists instead of nesting them.
Which of the following code snippets correctly creates a list of all even numbers from a nested list nested_list = [[1, 2], [3, 4, 5], [6]]?
This question tests understanding of **nested iteration and filtering** in Python lists.
- Option 2 – Correct: Uses a nested list comprehension to iterate through each sublist and pick only even numbers.
- Other options fail:
- Option 1 just copies sublists without flattening or filtering.
- Option 3 appends the entire sublist as elements, not individual numbers.
- Option 4 fails because
filter()operates on the top-level list and cannot directly access elements in nested lists.
Example output:
nested_list = [[1, 2], [3, 4, 5], [6]]
evens = [num for sublist in nested_list for num in sublist if num % 2 == 0]
print(evens) # Output: [2, 4, 6]
Key Takeaways:
- Nested list comprehensions are concise and powerful for flattening and filtering.
- Pay attention to the order of
forloops inside the comprehension. - Use the
ifcondition at the end to filter elements.
Which of the following code snippets correctly modifies only the inner list of a nested list without affecting the outer list references?
This is a highly tricky question testing **deep vs shallow copies** and **nested list mutability**.
- Option 4 – Correct: Using
copy.deepcopy()creates a completely independent copy of the nested list. Modifyinginnerdoes not affectouter. - Other options fail:
- Option 1 –
inner = outer[0]references the inner list directly, so changes reflect inouter. - Option 2 –
inner = outerreferences the whole outer list; any change affectsouter. - Option 3 –
inner = outer.copy()creates a shallow copy; inner lists are still referenced, so modifying them affectsouter.
- Option 1 –
Example output:
import copy
outer = [[1, 2], [3, 4]]
inner = copy.deepcopy(outer)
inner[0][0] = 100
print(outer) # Output: [[1, 2], [3, 4]]
print(inner) # Output: [[100, 2], [3, 4]]
Key Takeaways:
- Shallow copies (
copy()) do not copy nested objects. - Deep copies (
copy.deepcopy()) create full independent copies of nested structures. - Always be cautious with nested lists when modifying copies to avoid unintended side effects.
Explore More Python Exercises
You may also like these Python exercises:
Test Your Python Lists Knowledge
Practicing Python Lists? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python – Lists
Lists are one of the most versatile and widely used data structures in Python, and in this section on Solviyo, we focus entirely on them. Lists let us store collections of items in an ordered way, making them essential for everything from simple data storage to complex algorithms. We’ve created exercises that help you understand lists in a practical, hands-on way.
We start with the basics: creating lists, accessing items with indexing, and slicing them to get sublists. You’ll practice adding and removing elements, using built-in functions like append(), insert(), pop(), and remove(), and learning how lists grow and shrink dynamically. These exercises help you get comfortable with the building blocks of list manipulation.
Next, we move to slightly advanced topics. You’ll practice nested lists, iterating through lists with loops, and applying conditional logic to filter or process items. We also cover list comprehensions, which are a powerful and Pythonic way to create new lists in a concise and readable way. By working through these exercises, you’ll see how lists can make your code cleaner and more efficient.
What makes these exercises even more practical is the focus on real-world examples. You’ll practice tasks like storing and updating user input, processing data sets, or transforming lists into structured outputs. These aren’t just random drills—they’re exercises that mirror the kind of tasks you’ll encounter in projects, interviews, or coding challenges.
At Solviyo, we also emphasize understanding the “why” behind each operation. Every exercise comes with explanations so you can see why certain approaches work better, how to avoid common mistakes, and how to write more efficient and readable list code. This ensures you’re not just memorizing commands but actually learning to use lists effectively in your programs.
By the end of this section, you’ll be comfortable with everything from basic list operations to more advanced manipulations like nested lists and comprehensions. These exercises will strengthen your Python fundamentals and prepare you for real-world coding challenges. Start practicing Python lists with Solviyo today, and build a solid foundation for mastering data structures in Python.