Livecoding.tv Quiz of the Day: 26/10/2016

Python Quiz!

python-quiz

Answer:

The above code will output [], and will not result in an IndexError.

As one would expect, attempting to access a member of a list using an index that exceeds the number of members (e.g., attempting to access list[10] in the list above) results in an IndexError. However, attempting to access a slice of a list at a starting index that exceeds the number of members in the list will not result in an IndexError and will simply return an empty list.

What makes this a particularly nasty gotcha is that it can lead to bugs that are really hard to track down since no error is raised at runtime.

ENJOYING THIS POST?

Get More Benefits With LiveEdu Pro

To answer more Python Quizzes, check the ones from The Python Guru here: http://thepythonguru.com/python-guru-quiz/

If you want to explore more, visit our Python edu & tutorials section! Below are some examples:

A Python Game Boy emulator

Pokémon GO API’s

 

  • Why do you think it is a “gotcha”? You said “give me a list of all the elements of that list whose indices are greater than or equal to ten”. And it said “here you are”, and gave you the empty list. Why would it raise IndexError? If you ask for a list of elements that don’t exist, it is an empty list, of course.

    >>> [element for index, element in enumerate(list) if index >= 10]

    You don’t expect this to raise IndexError, do you? 🙂

Read previous post:
featuredimage
How To Create an App the Easy Way – Tips and Tricks from Pros

Learning how to make apps using a particular language and tools has never been easier. There are tons of tutorials...

Close