Python | Check if the list is in another list

Learn examples from DataCamp guru:

Method # 1: Using Nested Loops
This is a brute force method by which this task can be accomplished. In this case, the outer loop is designed to iterate over each element in the list, and the inner loop must add a similar element equal to the length of the corresponding tuple by the outer loop.

Output:

The original list: [(`1`, `4`, `6`), (` 5 `,` 8 `), (` 2 `,` 9 `), (` 1 `,)]
The modified and extended list i s: [(`1`, `4`, `6`), (`1`, `4`, `6`), (`1`, `4`, `6`), (`5`, `8`), (`5`, `8`), (`2`, `9`), (`2`, `9`), (`1`,)]

Method # 2: Using loop + chain()
This is another way to accomplish this task. In doing so, we shorten one cycle, the inner loop and multiply the tuples by one and smooth them using chain (). This can have some overhead depending on different cases.

# Python3 code for demonstrations
# Expand tuples by number in the list
# using a nested loop

 
# initialize the list of tuples

test_list = [( `1` , `4` , `6` ), ( ` 5` , `8` ), ( `2` , `9` ), ( ` 1` ,)]

 
# print the original list of tuples

print ( "The original list:" + str (test_list))

  
# Expand tuples by count in the list
# using a nested loop

res = []

for sub in range ( len (test_list)):

for ele in range ( len (test_list [sub] )):

res.append (test_list [sub])

 
# print result

print ( " The modified and extended list is: " + str (res))

< / tbody>

# Python3 code to demonstrate how it works
# Expand tuples by count in the list
# using loop + chain ()

from itertools import chain

 
# initialize the list of tuples

test_list = [( `1` , `4` , ` 6` ), ( `5`  , `8` ), ( ` 2` , `9` ), ( `1` ,)]

  
# print the original list of tuples

print ( "The original list:" + str ( test_list))

 
# Expand tuples by count in the list
# using loop + chain ()

res = []

for sub in range ( len (test_list)):

res.append ([test_list [sub]] * len (test_list [sub]))

res1 = chain ( * res)

res = list (res1)

 
# print result

print ( "The modified and extended list is:" + str (res))

Output:

The original list: [(`1`, `4`, `6` ), (`5`, `8`), (`2`, `9`), (`1`,)]
The modified and extended list is: [(`1`, `4`, `6`), (`1`, `4`, `6`), (`1`, `4`, `6`), (`5`, `8`), (`5`, `8 `), (` 2 `,` 9 `), (` 2 `,` 9 `), (` 1 `,)]

Learn examples from DataCamp guru: