List indexing, list slicing

The indexing and slice operation we saw with strings also work on lists.

list index, from left to right, index number starts from 0; from right to left(counting backward), index starts with negative number -1.

Access an element, similar to a string, Python uses square brackets to enclose the index number to access a item lst[i].

A list is mutable, means you can change its contents. We can assign new value to an element using list index:

lst[i] = new value

Example:

dates = ['Monday', 'Tuesday', 'Wed', 'Th', 'Fri', 'Sat', 'Sun']
# access to an element
print( dates[1] )         # Tuesday
print( dates[0] )         # Monday

# change the value of an element
dates[0] = 'First day'
print( dates[0] )         # First day

# the last item
print( dates[6] )         # Sun (the last item)
print( dates[-1] )        # Sun (also the last item)
print( dates[len(dates)-1] )   # Sun (the last item again)

In previous example, dates[6], dates[-1], and dates[ len(dates)-1 ] all points to the same item: the last element in the list.

Built-in function len()

Insert, similar to string, len( ) function reports on the size of an list.

Slice of a list

Remember range ( start, end, step) function? Lists 'understand' start, end, step too.

list[start:end:step] gives a list slice:

The first number is the list index that the slice starts, if omitted, default value is 0, means the slice starts from the beginning of the list;

The second number after : is the end index(not included in the slice), if omitted, the slice goes to the end of the list;

The last number is the step, default value is 1.

# list slice
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

print(numbers[8:])    # [9, 10, 11, 12]

print(numbers[:4])    # [1, 2, 3, 4]

print(numbers[1:6])   # [2,3,4,5,6]

print(numbers [: : 3])   # [1, 4, 7, 10] (every third number)

We can use list index to reverse a list:

# reverse list
num = [0,1,2,3,4,5,6]
numR = num[ : : -1]   # reverse a list, from end to start, going backward
print (numR)          # [6,5,4,3,2,1,0]

num2 = num[4:1:-1]  
print(num2)        # [4, 3, 2] (a piece of backward list

results matching ""

    No results matching ""