Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explain the first colon in Python slice syntax list[::-1] [duplicate]

Tags:

python

list

I recently read a code snippets about how to reverse a sequence

>> l = [1,2,3,4,5,6]
>> print l[::-1]

Output

>> [6,5,4,3,2,1]

How to explain the first colon in bracket?

like image 451
lazybios Avatar asked Dec 16 '22 00:12

lazybios


2 Answers

The colons with no values given means resort to default values. The default values for the start index when the step is negative is len(l), and the end index is -len(l)-1. So, the reverse slicing can be written as

l[len(l):-len(l)-1:-1]

which is of the form.

l[start:end:step]

Removing the default values, we can use it in a shorter notation as l[::-1].

It might be useful to go through this question on Python's Slice Notation.

like image 191
Sukrit Kalra Avatar answered Apr 27 '23 10:04

Sukrit Kalra


some_list[start:end:step]

When you ommit any of the slicing operands they take on default values. Default values for start, end and step: start - the beginning of an indexated iterable which is always of an index 0 when step is positive, end - the ending index of an indexated iterable which is always its length (following the same convention as range) when step is positive, step - the default step is always one.

When you're using a minus sign on step omitting other operands you're basically saying "return a reversed list".

EDIT: Funny, but

[1,2,3,4,5,6][5:-7:-1]

returns the same result as

[1,2,3,4,5,6][::-1]

in Python3. Can anyone comment on to why? That means that default values of start and end actually rest upon the step operand (more specifically its sign).

like image 41
Alisa D. Avatar answered Apr 27 '23 10:04

Alisa D.