Home > database >  Loop backwards starting in value (list)
Loop backwards starting in value (list)

Time:11-02

If i have a list calle dates (for example) that goes like this: [2022,2021,2020....] Until 20 or 30 values. And I reverse it with

reversed(list)

So it looks like this now: [1980.1981,1982...] How can I make a loop that starts in value 2020 for example and goes till 2022? So far i tried in the loop something like this:

for i in reversed(range((len(dates)))):

Which gives me the second list i wrote up, but i can't make it start in a certain index with:

for idx in reversed(range(3,(len(dates)))):

Any ideas on how to fix this? Thank you.

CodePudding user response:

If you know the start index you need the loop to start with you can use slicing like:

for item in dates[2::-1]:

which will loop backwards starting with the third item (with index 2) in the list down to its first element (with index 0) or

for item in reversed_dates[-3:]: 

which will loop starting with the third item counted from the end of the list to the list end.

And if you want to loop over the indices you can use the appropriate range() to get the right indices like:

for indx in range(2,-1,-1): 

or

for indx in range(-3, 0): 

Notice that the pieces of information you are probably missing is that you can use a negative step to loop backwards, both using slices and using range() and you can use negative indices in a slice to address items at a given distance from the end of a list.

CodePudding user response:

I hope this is what you're looking for.

year_list: list = [2025, 2024, 2023, 2022, 2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014, 2013, 2012, 2011, 2010]

# added 1 because the index begins from 0
# modify index(2020) to any year you would like your loop to begin from
index: int = year_list.index(2020)   1
year_list.sort(reverse=False)

# result: [2020, 2021, 2022, 2023, 2024, 2025]
print(year_list[-index::1])
  • Related