Imagine I have a list of values and I want to compare current value with previous value of the list using for loop. How to do that?
            Asked
            
        
        
            Active
            
        
            Viewed 1,608 times
        
    -1
            
            
        - 
                    1you just use the previous index...? if the current index is `i`, the previous element is at `i-1` – Chase Jun 22 '20 at 12:17
- 
                    Does this answer your question? [Python loop that also accesses previous and next values](https://stackoverflow.com/questions/1011938/python-loop-that-also-accesses-previous-and-next-values) – DarrylG Jun 22 '20 at 12:40
2 Answers
1
            Instead of doing your for loop like this (which is the preferred way)
for element in list:
    do_something()
You can do this:
for i in range(len(list)):
    element = list[i]
    previous_element = list[i-1]
    do_something()
Pay attention that in the first iteration, i will be 0 so list[i-1] will give the last element of the list, not the previous, since there is no previous.
 
    
    
        debsim
        
- 582
- 4
- 19
 
    