Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Enumerate with 'for'. Why doesn't it make an error?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading