Search code examples
pythonloopsnestedlist-comprehension

List comprehension on nested for loop


I have a list:

l1 = [1,2,3,6,8,1,2,3]

I want to iterate over list and print list of numbers starting and ending with same number.I have done it with for loop:

iniatializing = 1
for i in l1:
 for j in range(iniatializing,len(l1)):
     if i == l1[j]:
         starting_point =l1.index(i)
         print(l1[starting_point:j+1])
     iniatializing += 1

But how can this be done by using list comprehension?


Solution

  • I suppose what you want to achieve is:

    For each i, j (i < j), if l1[i]==l2[j], print the subset between i and j.

    n = len(l1)
    [l1[i:j+1] for i in range(n) for j in range(i+1, n) if l1[i] == l1[j]]
    

    EDIT: answer to the question about the original implementation.

    l1 = [1,2,3,6,8,1,2,3]
    
    iniatializing = 1
    for i in l1:
     for j in range(iniatializing,len(l1)):
         if i == l1[j]:
             starting_point =l1.index(i)
             print(l1[starting_point:j+1])
     iniatializing += 1
    
    #[1, 2, 3, 6, 8, 1]
    #[2, 3, 6, 8, 1, 2]
    #[3, 6, 8, 1, 2, 3]