Home > database >  How to loop from a particular index of an array in Python?
How to loop from a particular index of an array in Python?

Time:11-09

I am using a nested loop, and I want my inner loop to start from the index of the outer loop.

How can I implement this?

I want j to run from i till the end of the array.

nums = [2,7,11,15]

for i in nums:
    for j in nums:
        print(j)

CodePudding user response:

nums = [2,7,11,15]

for i, val in enumerate(nums):
    for j in nums[i:]:
        print(j)

This output is interested for you?

2 7 11 15 7 11 15 11 15 15

CodePudding user response:

Does it solve your problem?

nums = [2, 7, 11, 15]

for i in range(len(nums)):
    for j in range(i, len(nums)):
        print(j)

CodePudding user response:

If there is no duplicates in your array, you can do

for i in nums:
    for j in nums[nums.index(i):]:
         print(j)

else a more generic way is

for i in range(len(nums)):
    for j in nums[i:]:
         print(j)
  • Related