0Accessing 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 allow to use slice notation as lst[start:end:step]. The output of the slice notation is a new list containing elements from index start to end-1. If options are omitted start defaults to beginning of list, end to end of list 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 using step lengths of negative amounts, the starting index has to be greater than the ending index otherwise the result will be an empty list.

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

Using negative step indices are equivalent to the following code:

reversed(lst)[0:2] # 0 = 1 -1
                   # 2 = 3 -1

The indices used are 1 less than those used in negative indexing and are reversed.

Advanced slicing

When lists are sliced the __getitem__() method of the list object is called, with a slice object. Python has a builtin slice method to generate slice objects. We can use this to store a slice and reuse it later like so,

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:


List:
* List
* 0Accessing list values

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve