Looping is a process to repeat the same task multiple times. It provides sequential access to elements in the list. Comprehension offers a shorter syntax to iterate (loop) through list elements.
In previous article, we learned about How to Unpack List in Python. In this article we will learn about Python list loops and List comprehension in Python.
Python List Loops
Loops are an essential part of programming and generally used with the program workflow. Loops are used to iterate over collections like lists, tuples, sets, and dictionaries. Using loop we can iterate through the collection elements and access each element one-by-one. In this section, we explore how loops can be used to access list elements.
There are multiple ways we can use loop to access the elements in list.
- Python
for
Loop with List Elements - Python
for
Loop with List using Index - Python
while
Loop with List using Index - Create Nested List using Loop
- Create Filtered Lists in Python – Using Loop with Condition
for
Loop with List Elements
Python Python for
loop can be used to iterate through the elements of a list. The following example demonstrates this:
# Python for Loop with List Elements
sybytes_list = ['Python', 'AWS', 'Java', 'Azure', 'Data Science']
for element in sybytes_list:
print(element)
In this program, we have defined a list shbytes_list
. Using for
loop we are iterating through the list elements (one at a time) and printing its element value. for
loop execution will stop when it completes iteration through all elements of the list.
Output – Example Program – Python for Loop with List Elements
Python
AWS
Java
Azure
Data Science
for
Loop with List using Index
Python Python for
loop can be used to iterate through the sequence numbers, which are used as an index position to access list elements. The following example demonstrates this:
# Python for Loop with List using Index
sybytes_list = ['Python', 'AWS', 'Java', 'Azure', 'Data Science']
for index in range(len(sybytes_list)): # range through the length of a list
print(sybytes_list[index])
In this program, we are using range(len(sybytes_list))
function with the length of list. range()
is a Python’s built-in function, which will generate a sequence of numbers starting from 0
up-to length of list -1
. Sequence numbers are used as an index in the list. Using for
loop we will iterate through this sequence and will get the list element using the index position.
Output – Example Program – Python for Loop with List using Index
Python
AWS
Java
Azure
Data Science
List elements are accessed using their index positions and their values are printed as an output.
while
Loop with List using Index
Python Python while
loop can be used to access list elements using index positions. The following example demonstrates this:
# Python while Loop with List using Index
index = 0
while index < len(sybytes_list):
print(sybytes_list[index])
index += 1 # increase index position by 1
In this program, we are using a variable index
, initialized with value 0
. while
loop is used to check variable index
value less than the length of shbytes_list
and on each iteration we increment index
by 1. On each iteration we access the list element using index position.
Output – Example Program – Python while Loop with List using Index
Python
AWS
Java
Azure
Data Science
Create Nested List using Loop
We can create a list using a loop. The following example demonstrates this:
# Create Nested List using Loop
shbytes_list = ['Python']
for i in range(5):
shbytes_list = [shbytes_list]
print(shbytes_list)
We have created a list reference by variable shbytes_list
. Initially, this list has only 1 element. Using the for
loop which iterates 5 times, we are passing shbytes_list
in square brackets. This will create a new nested list and assign it to same variable again. This will generate a nested structure of lists.
Output – Example Program – Create List using Loop
[['Python']]
[[['Python']]]
[[[['Python']]]]
[[[[['Python']]]]]
[[[[[['Python']]]]]]
Create Filtered Lists in Python – Using Loop with Condition
Similar to accessing list elements in a loop, we can also create a list using loop. To select specific elements, we can check conditions on the list elements. Add only those elements in the list which pass the given condition. This will create a new filtered list. This example shows how to create a filtered list in Python by applying a condition during the loop.
# Create Filtered Lists in Python - Using Loop with Condition
sybytes_list = ['Python', 'AWS', 'Java', 'Azure', 'DataScience']
new_shbytes_list = [] # Defined a new empty list
for element in sybytes_list:
if "z" in element: # checking for condition
new_shbytes_list.append(element) # condition passed elements added to new list
print(new_shbytes_list) # print elements in new filtered list
In this program, we have created 2 lists => shbytes_list
with 5 elements and new_shbytes_list
an empty list. Using for
loop, we are iterating through the elements of shbytes_list
and checking for if
condition on each iterated element. If element passed the condition, then that element is added into the new list.
Output – Example Program – Create Filtered Lists in Python
['Azure']
From the program output, only element Azure
has z
in it from the given elements of the list.
List Comprehension in Python
List comprehension in Python, provides a more concise syntax for looping through list elements. List comprehension uses for
loop and can also include conditions to filter elements.
The basic syntax for list comprehension in Python is:
new_shbytes_list = [expression for item in iterable if condition == True]
Let’s see the different ways to use list comprehension in Python to create a new filtered list.
- List Comprehension – New List without
if
Condition - List Comprehension – New List with
if
Condition
if
Condition
Python List Comprehension – New List without # List Comprehension - New List without if Condition
sybytes_list = ['Python', 'AWS', 'Java', 'Azure', 'DataScience']
new_shbytes_list_4 = [element for element in sybytes_list] # Comprehension
print(new_shbytes_list_4)
List comprehension in Python uses for
loop to iterate through the elements in sybytes_list
and returned the iterated element as an output. Returned elements was collected within square brackets ([]
) to create a new list.
Output – Example Program – List Comprehension – New List without if Condition
['Python', 'AWS', 'Java', 'Azure', 'DataScience']
From the program output, new list new_shbytes_list_4
has all elements as was in the iterated list.
if
Condition
Python List Comprehension – New List with # List Comprehension - New List with if Condition
sybytes_list = ['Python', 'AWS', 'Java', 'Azure', 'DataScience']
print("\ncreate a new list using list comprehension and if-in condition")
new_shbytes_list_2 = [element for element in sybytes_list if "z" in element]
print(new_shbytes_list_2)
print("\ncreate a new list using list comprehension and if condition")
new_shbytes_list_3 = [element for element in sybytes_list if element != "Java"]
print(new_shbytes_list_3)
# create a new list using list comprehension and range function
print("\ncreate a new list using list comprehension and range function")
new_shbytes_list_5 = [element for element in range(10) if element > 3]
print(new_shbytes_list_5)
Output – Example Program – List Comprehension – New List with if Condition
create a new list using list comprehension and if-in condition
['Azure']
create a new list using list comprehension and if condition
['Python', 'AWS', 'Azure', 'DataScience']
create a new list using list comprehension and range function
[4, 5, 6, 7, 8, 9]
Summary
In this article, we explored loops and comprehensions in Python lists. We covered the following concepts:
- Python List Loops
- Python for Loop with List Elements
- Python for Loop with List using Index
- Python while Loop with List using Index
- Create Nested List using Loop
- Create Filtered Lists in Python – Using Loop with Condition
- List Comprehension in Python
- List Comprehension – New List without if Condition
- List Comprehension – New List with if Condition
Code snippets and programs related to Loops and List Comprehension in Python, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.
Interview Questions & Answers
Q: How can we use nested loops in a list comprehension?
Nested loops can also be used in list comprehensions by including multiple for
clauses.
nested_list = [[x, y] for x in [2, 4, 6] for y in [4, 16, 36]]
This list comprehension is equivalent to the following nested for
loops:
nested_list = []
for x in [2, 4, 6]:
for y in [4, 16, 36]:
nested_list.append([x, y])
- This creates all possible pairs of the elements from the two lists
[2, 4, 6]
and[4, 16, 36]
. - The result is a nested list (list of list) –
[[2, 4], [2, 16], [2, 36], [4, 4], [4, 16], [4, 36], [6, 4], [6, 16], [6, 36]]
.
Q: What are the advantages and disadvantages of using list comprehensions?
Advantages:
- Readability – For simple tasks, list comprehensions are more readable and concise compared to
for
loops. - Performance – List comprehensions are much faster than equivalent
for
loops because they are optimized for Python’s internal execution. - Compactness – Concise code, reduces the amount of code needs to write.
Disadvantages:
- Readability in complex cases – In case of complex logic, list comprehensions can become hard to read and difficult to understand. In complex scenarios,
for
loop is easy to read and understand. - Debugging – list comprehensions are hard to debug than
for
loops because the entire operation is on a single line. - Limited to lists – List comprehensions are specifically for creating lists, whereas
for
loops can be used for any iterable operations.
Q: Give an example of list comprehension to flatten a list of lists?
A list of lists (i.e., a two-dimensional list or nested list) can be converted to a single list using nested list comprehension.
list_of_lists = [[2, 4, 6], [8, 10, 12], [14, 16, 19]]
flatten_list = [item for sub_list in list_of_lists for item in sub_list]
- First
for
loop – Iterates over each sub_list inlist_of_lists
. - Second
for
loop: Iterates over each item in the currentsub_list
. - Expression:
item
is added to the final flattened list. - Final elements in
flatten_list
list will be[2, 4, 6, 8, 10, 12, 14, 16, 19]
.
Q: Is it possible to modify a list in place using a list comprehension?
No, modification of a list in place using a list comprehension is not possible. List comprehensions are used to create new lists rather than modifying existing ones. To modify a list in place, we should use a for
loop or other methods like map()
or list slicing.
Q: Explain the difference between a list comprehension and a generator expression.
Both list comprehensions and generator expressions are used to create iterables, but both have some important differences:
- List Comprehension creates a list in memory.
- Evaluates immediately and stores all the values in the list.
- Syntax –
[expression for item in iterable if condition]
. - Example –
[x**2 for x in range(10)]
creates a list of squares.
- Generator Expression
- Creates a generator object, which can be iterated over to generate items on the fly.
- Evaluates lazily, producing one item at a time and thus more memory-efficient, especially for large datasets.
- Syntax –
(expression for item in iterable if condition)
. - Example –
(x**2 for x in range(10))
creates a generator that yields squares one by one.
We should use list comprehensions when we need the entire list in memory, and use generator expressions when we need to iterate over items one at a time without storing them all at once.
Related Topics
- Understanding Lists in Python: A Comprehensive GuideLists in Python List is a core datatype in Python. Lists are sequences used to store elements (collection of data). Lists are similar to Arrays but are of dynamic size. It means the size of the list can be increased or decreased as we add or remove elements from the list. Understanding Python Lists: A…
- How to Create List in Python | Python List Creation Methods ExplainedList is a sequence data type used to store elements (collection of data). Lists are similar to Arrays but have a dynamic size, meaning the list size can increase or decrease as elements are added or removed. A list is a core data type in Python, along with Tuple, Set and Dictionary. Lists in Python…
- How to Access List Elements by Index in Python (with Example Programs)Python list elements are stored based on their index positions and can be accessed by their index positions, which allows to quickly retrieve specific element from the list. Index assignment to list element in Python, is similar to index assigned in Array elements. Understanding how to access list elements by index is crucial for data…
- Python List Index Method Explained with Examples | Get Element Position in ListElements in a Python list are stored based on their index positions. Lists in Python provides an index(arg) method to get the index position of an element within a list. In the previous article How to Access List Elements by Index, we learned how to access a list element using its index position. In this…
- Append Elements to List – Python | Add Elements with Append MethodIn Python, elements in a list can be added using the append(element) method. This method allows us to add elements to the end of a list easily. In the previous articles, we explored accessing list elements by index and using the list index method to retrieve an element’s position. This article covers appending new elements…