Updating a list using python list comprehension
-
A list of lists without keys
As an example, consider a list of books with book id, book name and the price. We are going to add a new column tax to the list, which is 10% of the book price. Then we will update the final price by adding this tax amount also.
See sample code below.Copiedbooks = [ [1, 'Book 1', 100.50 ], [2, 'Book 2', 80.75 ], [3, 'Book 3', 50.00 ] ] #Find new price after adding tax newPrice = [ [ b[0], b[1], float(b[2] / 10), b[2] + float(b[2] / 10) ] for b in books] print(newPrice)
[ [1, 'Book 1', 10.05, 110.55], [2, 'Book 2', 8.075, 88.825], [3, 'Book 3', 5.0, 55.0] ]
-
If list has data in the form of key-value pairs
The above list may some times be difficult to work with, because we can't link any name to the column. We will have to use positional parameters to access and modify data. To overcome this, we can keep data as key-value pairs.
Using list comprehension to update data is slightly different in such type of lists. To update an existing column value or to add a new column and update its data, we are going to use a python library named operator.
After this, use the operator.setitem() function, to update the data. operator.setitem() should have 3 parameters; list item, key name and the new value.
Copiedimport operator books = [ {'id': 1, 'name': 'Book 1', 'price': 100.50 }, {'id': 2, 'name': 'Book 2', 'price': 80.75 }, {'id': 3, 'name': 'Book 3', 'price': 50.00 } ] #Add new column tax [operator.setitem(b, "tax", float(b["price"] / 10) ) for b in books] #Find new price after adding tax [operator.setitem(b, "price", b["price"] + b["tax"] ) for b in books] print(books)
[ {'id': 1, 'name': 'Book 1', 'price': 110.55, 'tax': 10.05}, {'id': 2, 'name': 'Book 2', 'price': 88.825, 'tax': 8.075}, {'id': 3, 'name': 'Book 3', 'price': 55.0, 'tax': 5.0} ]