Search code examples
pythonpython-3.xindices

Why does slice(10, 50, 2).indices(10) return (10, 10, 2)?


#!/usr/bin/python
# 1.11. Naming a Slice
# Problem: Your program has become an unreadable mess of 
# hardcoded slice indices and you want to clean it up.

###### 0123456789012345678901234567890123456789012345678901234567890'
record = '....................100          .......513.25   ..........'  
cost = int(record[20:32]) * float(record[40:48])

print (cost)

# name the slices
SHARES = slice(20,32)
PRICE = slice(40,48)

cost = int(record[SHARES]) * float(record[PRICE])
print (cost)


items = [0, 1, 2, 3, 4, 5, 6]
a = slice(2, 4)

print (items[2:4])
print (items[a])

items[a] = [10,11]
print (items)

del items[a]
print (items)


a = slice(10, 50, 2)
print (a.start, a.stop, a.step)


s = 'HelloWorld'
indice = a.indices(len(s))
print (indice)

for i in range(*a.indices(len(s))):
    print(s[i])

This is the example in Chapter 1.11 of the Python Cookbook.

print (indices)

This should give me (5,10,2) but it gives me (10,10,2). Then the following for-loop did not print anything.

Why the results shown of my code is not like in the book?


Solution

  • This is actually an error in the book. If you check the errata and scroll down to page 19, there is this description:

    This example "a.indices(len(s))" leads to output that differs from the output as printed in the book, assuming the slice a is the slice a as shown in the example just above. It would work in the way shown, if a were slice(5, 50, 2) or so. Or am I wrong?

    Note from the Author or Editor: Change example mid-page to this:

    >>> a = slice(5, 50, 2)
    >>> a.start
    5
    >>> a.stop
    50
    >>> a.step
    2
    >>>
    

    Problematic example at bottom should then work.