-1

I know that enumerate function gives a index and element, repectively.

for idx, batch in enumerate(['A', 'B', 'C']):
   print(batch[0]) 

results :

A
B
C

is okay, while

print(batch[1]) 

gets error, string index out of range.

What I want to ask is,

for idx, batch in enumerate(['A', 'B', 'C']):
   print(batch[0:6]) 

get result

A
B
C

especially, it is not just for 6. 7,8, or anything bigger than 0(integer) makes the result.

Also, batch[0:0] did not make an error. Why is that?

JAEMTO
  • 209
  • 3
  • 15
  • 1
    why do you use enumerate when you don't use the `idx` variable? – thebjorn Nov 17 '21 at 08:32
  • If `batch` is the string `'A'` then `batch[0]` is the character A, and there is no `batch[1]`. – khelwood Nov 17 '21 at 08:33
  • 2
    This has nothing to do with `enumerate` or for loops; you can replicate the same behavior with just a single string. From [this answer on slices](https://stackoverflow.com/a/509295/12975140): "Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for `a[:-2]` and `a` only contains one element, you get an empty list instead of an error." – CrazyChucky Nov 17 '21 at 08:34
  • @CrazyChucky Well from my question, batch[0:5] means : batch[0], batch[1]..... Then batch[0] is okay, but when it goes to batch[1], then why no error happens? So what you mean is I just got an empty list? – JAEMTO Nov 17 '21 at 08:39
  • 1
    As mentioned in the answer I linked and quoted, that's simply how slices work in Python. `batch[1]` would throw an error, yes. But slices don't throw index errors if the sequence you're slicing runs out of items. – CrazyChucky Nov 17 '21 at 08:41
  • @thebjorn I used index too in my code but I was just curious – JAEMTO Nov 17 '21 at 08:42

1 Answers1

2

This has to do with the behavior of the slicing operator on strings:

As you are enumerating a list of strings, the slicing operator acts on each string. When one of the boundaries in the slicing operator exceeds the string's boundaries, no exception is raised. The slicing operator's boundaries are silently rectified.

For example, suppose we have the string:

s = 'Hello World!'

Then s[6:20] will generate 'World!', even though 20 exceeds the string's upper boundary.

Nir H.
  • 550
  • 2
  • 9