1

I have learned in class that for Python, characters stars from [0]. For example in Monty Python, 'M'=0, 'o'=1, 'n'=2, 't'=3, 'y'=4, ' '=5, 'P'=6, 'y' = 7, 't' = 8, 'h'=9, 'o' = 10, and 'n' = 11.

But I am confused when I saw the following operation on NLTK:

genre_word = [(genre, word) for genre in ['news', 'romance']
                            for word in brown.words(categories=genre)]

genre_word[:4]
genre_word[-4:]

I thought all character numbering starts with [0]. What does the [-4:] means?

amanb
  • 5,276
  • 3
  • 19
  • 38
Gmpt
  • 31
  • 1
  • 1
  • 2
  • The some_list[-n] syntax gets the nth-to-last element. So some_list[-4] gets the last four elements. – Nandhini Mar 18 '19 at 05:12

3 Answers3

1

For any iterable in python [-4:] denotes the indexing of last four items of that iterable. For example :

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

[3, 4, 5, 6]

str1 = 'Hello world'
str1[-4:]

'orld'

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
1

It gets the last four elements of the sequence:

>>> l = [1,2,3,4,5,6,7,8,9]
>>> l[-4:]
[6, 7, 8, 9]
>>> 
Simon
  • 9,762
  • 15
  • 62
  • 119
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

As you said in python the indexing of an array starts with 0

let us say

my_word = 'hello world'
print(my_word[0])  #prints 'h'

in python we also have a feature to index from the last

let us say

my_word = 'hello world'
print(my_word[-1]) # prints 'd'
# - stands from last starting with index 1
print(my_word[-4:]) # prints 'orld'
# if you know the length you can directly use
print(my_word[7:])  # prints 'orld'

This feature helps you to print the values indexing from last if you don't know the length

Bharghava
  • 21
  • 4