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.
length() and size() 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 value 10 from 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 True if the element is present, False otherwise.
Example:
my_list = [10, 20, 30, 50]
print(50 in my_list) # Output: True
print(100 in my_list) # Output: False
Methods like has() or contains() do not exist for Python lists.
Accessing my_list[50] will try to access the element at index 50, which may raise an IndexError.
Tip: Use the in operator for simple and readable membership checks.
Which of the following operations combines two listslist1 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 + list2 returns a new list containing all elements from both lists.
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 del with 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]
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.
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.
Quick Recap of Python Lists Concepts
If you are not clear on the concepts of Lists, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.
What is a Python List?
A Python list is an ordered collection of items in Python that can store elements of different data types such as integers, strings, floats, or even other lists. Python lists are mutable, which means you can modify, add, or remove elements after creation. Lists are one of the most commonly used Python data structures for storing and manipulating sequences of data.
Creating Python Lists
You can create a Python list using square brackets[] or the list() constructor.
Python lists are mutable. You can change elements, add new items, or remove items after creating the list.
Operation
Python List Method / Syntax
Example
Change element
list[index] = value
animals[1] = "tiger"
Add element
append(), insert()
animals.append("koala")
Remove element
remove(), pop(), del
animals.pop()
animals = ["lion", "leopard", "cheetah"]
animals[1] = "tiger" # Change element
animals.append("koala") # Add element
animals.pop() # Remove last element
Slicing Python Lists
Slicing allows you to access a sub-list from a Python list using a start and end index.
Practicing Python Lists? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python Lists Exercises
Welcome to Solviyo’s Python Lists exercises, designed to help you master one of the most versatile and widely used data structures in Python. Lists allow you to store collections of items in an ordered way, making them essential for both simple data storage and complex algorithms. These exercises guide you step by step, from basic operations to advanced list manipulations.
What You Will Learn
In this set of Python Lists exercises, you will explore:
Creating lists and accessing elements using indexing and slicing.
Adding, removing, and modifying list elements using methods like append(), insert(), pop(), and remove().
Understanding dynamic resizing of lists and working with nested lists.
Iterating through lists using loops and applying conditional logic to process elements.
Using list comprehensions to create concise and readable new lists.
Applying lists in practical, real-world scenarios such as data storage, processing datasets, and structuring outputs.
Recognizing common mistakes and learning best practices for efficient and readable list code.
Why Learning Python Lists Matters
Lists are a fundamental part of Python programming. Mastering lists allows you to store, manipulate, and access data efficiently, which is essential for almost every Python program. Understanding list operations, nested lists, and comprehensions prepares you for more advanced data structures, algorithms, and coding challenges.
Start Practicing Python Lists Today
By completing these exercises, you will gain confidence in using lists for a variety of tasks, from simple storage to advanced data manipulation. Each exercise includes explanations to reinforce learning and help you apply lists effectively in real projects. Start practicing Python Lists exercises now and build a strong foundation for mastering data structures in Python.
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.