Search code examples
pythonloopsfor-loopindexingwhile-loop

hi! I want to loop over this list


I want to loop over this list one item at a time, I want to have 0th element as constant and for every 0th element I want to have 1st,2nd,..... till last element and then repeat the process I.e for 1st element I want to have 2nd,3rd,4th.... last element and so on. I have tried for loop and while loop, but due to index error in the first cycle it is not going to the second cycle. Kindly guide. Thankyou in advance.

--

type here
ls = ['aa','bb','cc','dd','ee','ff','gg','hh']

for i in range(len(ls)):
    print("this is first loop", i)
    j=i
    while j <= len(ls):
        print("this is second loop", j+1)
        print("this is second loop", ls[j+1])
        j+=1
    this is first loop 0
    this is second loop 1
    this is second loop bb
    this is second loop 2
    this is second loop cc
    this is second loop 3
    this is second loop dd
    this is second loop 4
    this is second loop ee
    this is second loop 5
    this is second loop ff
    this is second loop 6
    this is second loop gg
    this is second loop 7
    this is second loop hh
    this is second loop 8
    Traceback (most recent call last):
    print("this is second loop", ls[j+1])
    IndexError: list index out of range

Solution

  • You can use a second for-loop like this:

    ls = ['aa','bb','cc','dd','ee','ff','gg','hh']
    
    for i in range(len(ls)):
        print("this is first loop", i)
        for j in range(i + 1, len(ls)):
            print("this is second loop", j)
            print("this is second loop", ls[j])