Index lookup is a way to access a specific element or slice of elements from a string or a list in Python. The syntax for index lookup varies slightly between strings and lists, but the general concept is the same.
For strings, you can access a specific character by specifying its index in square brackets []. The index starts at 0 for the first character, and continues incrementally for each subsequent character. Here's an example:
my_string = "Hello, world!"first_char = my_string[0]second_char = my_string[1]print(first_char) # Output: "H"print(second_char) # Output: "e" |
You can also use negative indices to access characters from the end of the string. The last character has an index of -1, the second to last has an index of -2, and so on. Here's an example:
my_string = "Hello, world!"last_char = my_string[-1]second_last_char = my_string[-2]print(last_char) # Output: "!"print(second_last_char) # Output: "d" |
For lists, the syntax for index lookup is the same as for strings. You can access a specific element by specifying its index in square brackets []. Here's an example:
my_list = [1, 2, 3, 4, 5]first_element = my_list[0]second_element = my_list[1]print(first_element) # Output: 1print(second_element) # Output: 2 |
You can also use negative indices to access elements from the end of the list. The last element has an index of -1, the second to last has an index of -2, and so on. Here's an example:
my_list = [1, 2, 3, 4, 5]last_element = my_list[-1]second_last_element = my_list[-2]print(last_element) # Output: 5print(second_last_element) # Output: 4 |
In addition to accessing single elements, you can use index lookup to access a slice of elements from a string or a list. This is done by specifying a range of indices separated by a colon : inside the square brackets []. Here's an example:
my_string = "Hello, world!"first_five_chars = my_string[0:5]print(first_five_chars) # Output: "Hello" |
In this example, the slice includes characters with indices from 0 to 4 (inclusive), but excludes the character with index 5. This is called a half-open interval. You can omit the starting or ending index to include all characters up to or from the beginning or end of the string or list, respectively.