Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Built-in Functions Common to Most Data Structures
9. index()
Summary

Instruction

Perfect! The last function we'll discuss in this part is index(). It returns the index of the element specified in the parentheses. If the element appears more than once, its first index will be returned. Take a look:

requests_processed = [12, 18, 15, 23, 24, 8, 0, 18, 14, 13]
requests_processed.index(18)

The code above returns a 1 because the number 18 appears at the second position. (Remember, index() only returns where the element first appears and ignores the other appearances.)

Behind the scenes, index() iterates over the indexes of all list elements and returns the current index as soon as it finds the first occurrence of the given value. Again, it's not very difficult to write such a function yourself, but using index() is very convenient and makes your intention clear to all Python developers.

Exercise

Write a function named get_string_until(string, letter) that returns all characters from the string until the first occurrence of the letter (inclusive).

For example, given this input:

get_string_until('here comes the rain again', 'a')

The function should return:

'here comes the ra'

Assume that there is at least one letter in string.

Stuck? Here's a hint!

To get the beginning of a string until a specific index (inclusive), use:

string[:specific_index + 1]