john adam
john adam

Reputation: 15

Find an element in a sub list, and when this element is found, append all other elements in the list to another list

I have a big list which contains other sub lists inside it, i want to find specific element in sub lists, and when i find the element in one of sub lists, i want to take other elements in this specific sub list and append it in another list.

big_list= [['A','B','C'], ['D','E','F'], ['Find this:','Get this','and that'], ['G','H','I'], ['Find this:','Try this','Try that']]

I have done this:

    New_list =[]
    prefixes = ('Find this:') #it's an element in a sub list
    for sub_list in big_list[:]:
        for element in sub_list[:]:
            if prefixes in element:
               New_list.append(element)
   print(New_list)

In my code the result is:

New_list = ['Find this:', 'Find this:']

i want to get the other elements in this specific list, so the result is:

New_list = ['Find this:','Get this','and that', 'Find this:','Try this','Try that']

Upvotes: 0

Views: 49

Answers (2)

Vishal Singh
Vishal Singh

Reputation: 6234

Make sure to do a deep copy of the sub_lst otherwise changes made to the big_list will also reflect in the new_lst.

from copy import deepcopy

prefix = "Find this:"
new_lst = [deepcopy(sub_lst) for sub_lst in big_list if prefix in sub_lst]

A little bit about shallow and deep copy operations.

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively,
    inserts copies into it of the objects found in the original.

Upvotes: 0

nasc
nasc

Reputation: 299

I feel like you are making things unnecessarily complicated. The in in if prefixes in element: can directly search in lists.

New_list =[]
prefixes = 'Find this:' 
for sub_list in big_list:
    if prefixes in sub_list:
        New_list.append(sub_list)
print(New_list)

This should work

Upvotes: 1

Related Questions