Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does n[::-1] means in Python?

Tags:

python

string

I have a string n = "abc".

I want to reverse it and found a solution like n[::-1].

What is the meaning of all 3 arguments?

like image 443
Gourav Singla Avatar asked Feb 16 '15 06:02

Gourav Singla


People also ask

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

What does a \n mean in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text.

What does \r and \n do in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.

What is if I & 1 in Python?

it is binary "and". Eg 7 = 111 111 and 001 = 1 Actually it is a test if a number i is odd. if yes, the result is 1.


1 Answers

It means, "start at the end; count down to the beginning, stepping backwards one step at a time."

The slice notation has three parts: start, stop, step:

>>> 'abcdefghijklm'[2:10:3]  # start at 2, go upto 10, count by 3
'cfi'
>>> 'abcdefghijklm'[10:2:-1] # start at 10, go downto 2, count down by 1
'kjihgfed'

If the start and stop aren't specified, it means to go through the entire sequence:

>>> 'abcdefghijklm'[::3]  # beginning to end, counting by 3
'adgjm'
>>> 'abcdefghijklm'[::-3] # end to beginning, counting down by 3
'mjgda'

This is explained nicely in Understanding slice notation, in the Python docs under "extended slicing", and in this blogpost: Python Slice Examples: Start, Stop and Step

like image 181
Raymond Hettinger Avatar answered Sep 19 '22 13:09

Raymond Hettinger