Appending Item to Lists of list using List Comprehension | Python
Last Updated :
06 Feb, 2024
If you are a Python user, you would know that in Python, we can use the append() method to add an item to an existing list. This list may already contain other items or be empty. Further, the item to be added can simply be a number a character, or even an entire tuple or list. However, if you are trying to append an item to lists within a list comprehension, then you might be having a hard time.
Although list comprehensions are quite useful since they help in creating new sequence data types quickly and shortly without making use of for loops, using the append() function within a list comprehension isn’t the same as it is normally. But worry not because in this article, we are going to discuss all appending items to lists within a list comprehension in Python.
Append an Item to Lists Within A List Comprehension in Python
Below are some of the ways by which we can append an item to lists within a list comprehension in Python:
- Using the 'Or' operator
- Using a non-in-place operator like '+'
- Using List Comprehension without the assignment operator
- Using the Extend Method
Append an Item to Lists Within A List Using or Operator
To resolve the problem of getting 'None' values in the output, you can make use of the ‘or’ operator inside the list comprehension. You can see that this time the code runs as desired. This is because this time when the append() function returns ‘None’, which is a ‘False’ value, the ‘or’ operator further looks for a ‘True’ value to operate it with. And naturally, the ‘True’ value found is nothing but ‘x’(with an updated item) itself.
Python3
#list containing lists
squares = [[1, 1], [2, 4], [3, 9], [4, 16], [5, 25]]
#use list comprehension to append an item
squares = [x.append('10') or x for x in squares]
#print updated list
print(squares)
Output[[1, 1, '10'], [2, 4, '10'], [3, 9, '10'], [4, 16, '10'], [5, 25, '10']]
Using a Non In-Place Append Operator
By now, you know that the append() function works by updating list items in-place. However, to work in a list comprehension, we need an operator that does not update values in-place. Thus, instead of using append() to add item to lists within a list comprehension, you can make use of the ‘+’ operator as follows:
Python3
#list containing lists
squares = [[1, 1], [2, 4], [3, 9], [4, 16], [5, 25]]
#use list comprehension to append an item
squares = [x + [10] or x for x in squares]
#print updated list
print(squares)
Output[[1, 1, 10], [2, 4, 10], [3, 9, 10], [4, 16, 10], [5, 25, 10]]
Python Append List to a List Without the Assignment Operator
List comprehensions are meant to create new lists and not update the existing ones. This was the underlying reason why we were getting 'None' values with the in-place append() function. However, if we drop the assignment operator within a list comprehension, then we would be actually be getting the list comprehension to update the original list. This is nothing but the use of side effects of list comprehension which is not recommended. But still, here is the code for your reference:
Python3
#list containing lists
squares = [[1, 1], [2, 4], [3, 9], [4, 16], [5, 25]]
#use the append method inside list comprehension
[square.append(10) for square in squares]
#print updated list
print(squares)
Output[[1, 1, 10], [2, 4, 10], [3, 9, 10], [4, 16, 10], [5, 25, 10]]
Python Append List to a List Using Extend() Method
The Extend() method in Python works just like the append() method, except that it can add multiple elements to an iterable object instead of just one. Further, the extend() method also works as an in-place operator, which means that we are going to have the same problem in using it as we had with the append() method. However, we can again make use of the side effect of list comprehension by dropping the use of assignment operator like we did above. Again, this is not a recommended method to use.
Python3
#list containing lists
squares = [[1, 1], [2, 4], [3, 9], [4, 16], [5, 25]]
#use the extend method inside list comprehension
[square.extend([10]) for square in squares]
#print updated list
print(squares)
Output[[1, 1, 10], [2, 4, 10], [3, 9, 10], [4, 16, 10], [5, 25, 10]]
Conclusion
In this article, we looked at the problem that exists when we try to append items to lists within a list comprehension using the append() method because it is an in-place operator. We further discussed how we can solve the problem using the Python 'Or' operator and the non in-place '+' operator. Although doing this is quite simple with nested for loops, using a list comprehension might be necessary at a few places. Further, you can use the side effect of list comprehension if absolutely necessary. Hopefully, now you will be able to do it.
Similar Reads
Python List Comprehension and Slicing
Python's list comprehension and slicing are powerful tools for handling and manipulating lists. When combined, they offer a concise and efficient way to create sublists and filter elements. This article explores how to use list comprehension with slicing including practical examples. The syntax for
4 min read
How to Create a List of N-Lists in Python
In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
3 min read
Iterate through list of dictionaries in Python
In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use: [{'Python': 'Machine Learning', 'R': 'Machine learning'}, {'Python': 'Web development', 'Java Script': 'Web Development', 'HTML': 'Web Development'}, {'C++': 'Game Development', 'Python': 'Game
3 min read
Read a CSV into list of lists in Python
In this article, we are going to see how to read CSV files into a list of lists in Python. Method 1: Using CSV moduleWe can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.We can use other modules like pandas which are mostly used in ML appl
2 min read
Nested List Comprehensions in Python
List Comprehension are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. Neste
5 min read
Ways to create a dictionary of Lists - Python
A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key. Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
Ways to Iterate Tuple List of Lists - Python
In this article we will explore different methods to iterate through a tuple list of lists in Python and flatten the list into a single list. Basically, a tuple list of lists refers to a list where each element is a tuple containing sublists and the goal is to access all elements in a way that combi
3 min read
Map vs List comprehension - Python
List comprehension and map() both transform iterables but differ in syntax and performance. List comprehension is concise as the logic is applied in one line while map() applies a function to each item and returns an iterator and offering better memory efficiency for large datasets. List comprehensi
2 min read
List Comprehension in Python
List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques. For example
4 min read
Iterate over Two Lists with Different Lengths in Python
Iterating over two lists of different lengths is a common scenario in Python. However, we may face challenges when one list is shorter than the other. Fortunately, Python offers several methods to handle such cases, ensuring that our code is both readable and efficient. Using zip() function - Loop u
3 min read