[::-1] how it gives the reverse of list? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

[::-1] how it gives the reverse of list?

29th Sep 2019, 10:14 AM
Sharuk khan
Sharuk khan - avatar
2 ответов
+ 3
It is just agreed that negative steps would reverse the iterable. Theoretical definition: #(Does not handle arguments of nonsense.) def slice(iterable, start=None, end=None, step=1): #Handling None indices: if start == None: start = 0 if end == None: end = len(iterable) #Handling negative indices: start = start % len(iterable) end = (end - 1) % len(iterable) + 1 #If step is negative: if step < 0: start, end = end-1, start #Filling new_list: new_list = [] i = start if step > 0: while i < end: new_list.append(iterable[i]) i += step elif step < 0: while i > end: new_list.append(iterable[i]) i += step #Returning new_list as type of the initial iterable: return type(iterable)(new_list) a = list(range(10)) b = slice(a, 10, 0, -2) c = a[10:0:-2] #b equals c
29th Sep 2019, 10:27 AM
Seb TheS
Seb TheS - avatar
+ 2
check out this code for more info on reversing lists in Python https://code.sololearn.com/cWGyRXm9rC8i/?ref=app
29th Sep 2019, 12:50 PM
Brave Tea
Brave Tea - avatar