I have a list of lists like this,
big_list = [[1,3,5], [1,2,5], [9,3,5]]
sec_list = [1,3,5]
I want to iterate through the big_list
and check each list values against the sec_list
. While I check, I want to store the values that are not matching into a another list of lists. So, I did this:
sma_list = []
for each in big_list:
for i,j in zip(each, sec_list):
if i!=j:
sma_list.append(i)
I get the result like this:
[2, 9]
However, I need a list of lists like this,
[[2], [9]]
How can I achieve this?
Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element. Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.
Iterate over multiple lists at a time We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.
Use a nested for-loop to iterate through a nested list. Use a for-loop to iterate through every element of a list. If this list contains other lists, use another for-loop to iterate through the elements in these sublists.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.
Short answer,
sma_list.append([i])
Enclosing a value in square brackets makes it the first element of a one element list.
This will only work correctly if you have one missing element per list. You're much better off using a comprehension for the whole thing:
sma_list = [[i for i, j in zip(each, sec_list) if i != j] for each in big_list]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With