Use square brackets with a numeric position to retrieve one element from a string, list, or tuple: s[0] returns the first element and s[-1] the final one. A single index retrieves an element, while a slice such as s[2:5] retrieves elements up to, but not including, the ending position. section 4.3
Keep these indexing distinctions in mind:
- Single indexes must remain within the sequence bounds; slices tolerate endpoints beyond the data and stop at the available boundary. section 4.3
- An indexed element may have any type, while a slice preserves the sequence type: list slices remain lists and tuple slices remain tuples. section 4.3
- Use enumerate when iteration needs both each item and its numeric index; unpack its two-element results directly in the loop. section 2.15
A reusable first-and-last operation
def firstlast(sequence): return sequence[0] + sequence[-1] firstlast(('a', 'b', 'c')) # 'ac' firstlast((1, 2, 3, 4)) # 5 The same function works with different sequence types because both support numeric indexes. section 4.3
for index, one_letter in enumerate('abcd'):
print(f'{index}: {one_letter}')
Run the enumerate example to see each character paired with its numeric position. section 2.15














