How to run a nested loop in python inside list such that the outer loop starts from the next element of the list always and so on
Try this code !
For each iteration of outer loop, you need to iterate the inner loop from 1
increment to the range of list.
Code :
arr = [1,5,2,0,4,2,7]
for i in range(0,len(arr)):
print("Iteration # : ", i+1)
for j in range(i+1,len(arr)):
print("Outer loop value : " , arr[i] , " Inner loop value : " , arr[j])
Output :
Iteration # : 1
Outer loop value : 1 Inner loop value : 5
Outer loop value : 1 Inner loop value : 2
Outer loop value : 1 Inner loop value : 0
Outer loop value : 1 Inner loop value : 4
Outer loop value : 1 Inner loop value : 2
Outer loop value : 1 Inner loop value : 7
Iteration # : 2
Outer loop value : 5 Inner loop value : 2
Outer loop value : 5 Inner loop value : 0
Outer loop value : 5 Inner loop value : 4
Outer loop value : 5 Inner loop value : 2
Outer loop value : 5 Inner loop value : 7
Iteration # : 3
Outer loop value : 2 Inner loop value : 0
Outer loop value : 2 Inner loop value : 4
Outer loop value : 2 Inner loop value : 2
Outer loop value : 2 Inner loop value : 7
Iteration # : 4
Outer loop value : 0 Inner loop value : 4
Outer loop value : 0 Inner loop value : 2
Outer loop value : 0 Inner loop value : 7
Iteration # : 5
Outer loop value : 4 Inner loop value : 2
Outer loop value : 4 Inner loop value : 7
Iteration # : 6
Outer loop value : 2 Inner loop value : 7
Iteration # : 7
You should try to iterate with indexes directly instead of elements it would be easier to start from the nex position in your list :
your_list = [1,5,2,0,4,2,7]
for index in range(len(your_list)):
element_outer_loop = your_list[index]
for index2 in range(index+1, len(your_list)):
element_inner_loop = your_list[index2]
In the code that you have done you get bad result because your list contains multiple time a same value (2 for example) and when you call the index(sub_list1)
it will return the first corresponding elements so it will be good for the first 2 but for the next it will return the position of the first.
The enumerate() method adds counter to an iterable and returns it (the enumerate object).
yx = [1,5,2,0,4,2,7]
for index,sub_list1 in enumerate(yx):
for sub_list2 in yx[index+1:]:
print(sub_list2)