How to reverse a list upto a given index in Python

3 Answers

0 votes
lst = [1, 4, 8, 0, 7, 3, 9, 5, 6]

index = 5

part = lst[0:index]

part.reverse()

lst = part + lst[index:]
 
print(lst)

   
   
    
'''
run:
    
[7, 0, 8, 4, 1, 3, 9, 5, 6]
    
'''

 



answered Jul 3, 2022 by avibootz
0 votes
lst = [1, 4, 8, 0, 7, 3, 9, 5, 6]
 
index = 5
 
part = lst[0:index]
 
part.reverse()
 
lst[0:index] = part
  
print(lst)
 
    
    
     
'''
run:
     
[7, 0, 8, 4, 1, 3, 9, 5, 6]
     
'''

 



answered Jul 3, 2022 by avibootz
0 votes
def reverseUpToIndex(lst, index):
    if (index > len(lst)):
        print("Index out of range")
        return
      
    for i in range(0, (int)(index / 2)):
        temp = lst[i]
        lst[i] = lst[index - i - 1]
        lst[index - i - 1] = temp
          
lst = [1, 4, 8, 0, 7, 3, 9, 5, 6]
 
index = 5
 
reverseUpToIndex(lst, index);
  
print(lst)
    
    
     
'''
run:
     
[7, 0, 8, 4, 1, 3, 9, 5, 6]
     
'''

 



answered Jul 4, 2022 by avibootz

Related questions

1 answer 171 views
1 answer 167 views
1 answer 174 views
1 answer 164 views
1 answer 151 views
1 answer 162 views
1 answer 151 views
...