Accessing list values

suggest change

Python lists are zero-indexed, and act like arrays in other languages.

lst = [1, 2, 3, 4]
lst[0]  # 1
lst[1]  # 2

Attempting to access an index outside the bounds of the list will raise an IndexError.

lst[4]  # IndexError: list index out of range

Negative indices are interpreted as counting from the end of the list.

lst[-1]  # 4
lst[-2]  # 3
lst[-5]  # IndexError: list index out of range

This is functionally equivalent to

lst[len(lst)-1]  # 4

Lists support slice notation, lst[start:end:step]. The slice is a new list containing elements from index start up to but not including end. If an index is omitted, start defaults to the beginning of the list, end to the end, and step to 1:

lst[1:]      # [2, 3, 4]
lst[:3]      # [1, 2, 3]
lst[::2]     # [1, 3]
lst[::-1]    # [4, 3, 2, 1] 
lst[-1:0:-1] # [4, 3, 2]
lst[5:8]     # [] since starting index is greater than length of lst, returns empty list
lst[1:10]    # [2, 3, 4] same as omitting ending index

With this in mind, you can print a reversed version of the list by calling

lst[::-1]    # [4, 3, 2, 1]

When the step is negative and both indexes are given, the start index has to be greater than the end index. Otherwise the result is an empty list.

lst[3:1:-1] # [4, 3]

reversed(lst) is an iterator, so it cannot be sliced directly. This slice matches the first two items of the reversed list:

list(reversed(lst))[0:2]  # [4, 3]

Advanced slicing

When a list is sliced, its __getitem__ method is called with a slice object. slice is a built-in type you can call to store a slice and reuse it:

data = 'chandan purohit    22 2000'  #assuming data fields of fixed length 
name_slice = slice(0,19)
age_slice = slice(19,21)
salary_slice = slice(22,None)

#now we can have more readable slices
print(data[name_slice]) #chandan purohit     
print(data[age_slice]) #'22'
print(data[salary_slice]) #'2000'

This can be of great use by providing slicing functionality to our objects by overriding __getitem__ in our class.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents