Python – Rows with all List elements


When it is required to give the rows with all list elements, a flag value, a simple iteration and the ‘append’ method is used.

Example

Below is a demonstration of the same

my_list = [[8, 6, 3, 2], [1, 6], [2, 1,7], [8, 1, 2]]

print("The list is :")
print(my_list)

sub_list = [1, 2]

result = []
for row in my_list:

   flag = True

   for element in sub_list:
      if element not in row:
         flag = False
   if flag:
      result.append(row)

print("The resultant list is :")
print(result)

Output

The list is :
[[8, 6, 3, 2], [1, 6], [2, 1, 7], [8, 1, 2]]
The resultant list is :
[[2, 1, 7], [8, 1, 2]]

Explanation

  • A list of list is defined and is displayed on the console.

  • Another list with integer values is defined.

  • Another empty list is defined.

  • The list of list is iterated over and a flag value is set to ‘True’.

  • If the element present in the integer list is not present in the list, the flag value is set to ‘False’.

  • In the end, depending on the flag value, the output is determined.

  • If the value of flag is ‘True’, the element is appended to the empty list.

  • This is displayed as output on the console.

Updated on: 14-Sep-2021

589 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements