Python Negative Feed

I am currently reading Robert Sebest's Concepts of Programming Languages, 10th edition (2012). In the chapter on data types, she says: "Ruby and Lua support negative indexes, but Python does not." I thought negatives indices could be done in Python using list_name[-i] . What are negative indices?

+8
python subscript
source share
2 answers

Python, Lua, and Ruby support negative indexes. In Python, this feature was added as a footnote in version 1.4 and confirmed as extended slicing in version 2.3

On page 264 of Sebesta's book (10th ed.), He claims that Python does not support negative indexing on arrays. The source code was redesigned and republished as edition 6 in 2004, while Python 2.3 was released on July 29, 2003. I assume that the extended thread has been missed and has been erroneous since the sixth edition of Sebesta.

I cannot find errors for the 10th edition. You can send a letter to the author and inform him.

+6
source share

In Python and Ruby, a negative index indexes back from the end of the array. That is, when the index is negative, the length of the array is added to it.

This does not apply to Lua. A negative index does not really matter; it simply refers or creates a table entry with this negative number as a key.

Python 2.7.3:

 >>> a = [ 'x', 'y', 'z' ] >>> a ['x', 'y', 'z'] >>> a[-1] 'z' >>> a[-1] = 'm' >>> a ['x', 'y', 'm'] >>> 

Ruby 1.9.3:

 irb(main):001:0> a = [ 'x', 'y', 'z' ] => ["x", "y", "z"] irb(main):002:0> a => ["x", "y", "z"] irb(main):003:0> a[-1] => "z" irb(main):004:0> a[-1] = 'm' => "m" irb(main):005:0> a => ["x", "y", "m"] irb(main):006:0> 

Lua 5.2.3:

 > a = { 'x', 'y', 'z' } > for key, value in pairs(a) do print( key, value ) end 1 x 2 y 3 z > print( a[3] ) z > print( a[-1] ) nil > a[-1] = 'm' > print( a[-1] ) m > for key, value in pairs(a) do print( key, value ) end 1 x 2 y 3 z -1 m > 

JavaScript behavior is pretty similar to Lua behavior. You can use a negative index in an array, and in fact you can use any arbitrary string as an index. The JavaScript array is actually an object with some additional methods, properties ( .length ) and behavior (updating .length if necessary). When you use array[-1] , you add or reference a property with the key "-1" , and .length not updated.

Chrome 33:

 > var a = [ 'x', 'y', 'z' ]; undefined > a ["x", "y", "z"] > a[2] "z" > a[-1] undefined > a[-1] = 'm' "m" > a[-1] "m" > a[2] "z" > a ["x", "y", "z"] > for( var key in a ) console.log( key, a[key] ); 0 x 1 y 2 z -1 m undefined 

Do not be fooled by the undefined printed at the end - this is not part of the for( var key in a ) enumeration, it is simply printed there, because console.log() is the last expression evaluated in the loop, and it does not return value ( it just prints the value).

+1
source share

All Articles