Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of lists, iterating a list of lists

Tags:

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?

like image 712
user9431057 Avatar asked Oct 15 '18 00:10

user9431057


People also ask

Can you have a list of list of lists in Python?

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.

Can you loop through multiple 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.

How do you get into a nested list?

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.

Can you loop through a list?

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.


1 Answers

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]
like image 111
Mad Physicist Avatar answered Nov 15 '22 06:11

Mad Physicist