Python Programming - Accessing Lists

You can learn about List Manipulation in Python Programs with Outputs helped you to understand the language better.

Python Programming – Accessing Lists

Lists are container data type that acts as a dynamic array. In other words, the list is a sequence that can be indexed into and can grow and shrink. List elements have index numbers. Indexing and slicing operations on lists mostly work in the same way as they do with strings. List indexing is zero-based as it is with strings. Working from left to right, the first element has the index 0, the next has the index 1, and so on.
Num = [ 45 , 67 , 56 , 34 ]
print( Num ( 0 ) )
it prints 45 because the location of a list starts at position 0.

Indexing

The list data type is a container that holds a number of elements in a given order. For accessing an element of the list, indexing is used. Each item in a list corresponds to an index number, which is an integer value, starting with the index number 0 goes to length – 1. You can use indexing to change items within the list, by setting an index number equal to a different value. This example shows the items at index 0 and 1 of the list x.

>>> x = [ ‘ apple ‘ , ‘ banana ‘ , ‘ pear ‘ ]
>>> x[0]
‘apple’
>>> x [ 1 ]
‘banana’

Python allows negative indexing for its sequences. The negative indices are counted from the right. The index of -1 refers to the last item, -2 to the second last item, and so on until the leftmost element is encountered. The following example shows the items at index -1 and -2.
>>> x[-1]
‘pear’
>>> x[-2]
‘banana’
The literal representation of a list is square brackets containing zero or more items, separated by com-mas.
An individual element of a list can also be accessed through their indexes. For example,
>>> ch = [ ‘ 1 ‘ , ‘ o ‘ , ‘ w ‘ , ‘ e ‘ , ‘ r ‘ ]
>>> ch[0]
‘ 1’
>>> ch[4]
‘ r ‘
>>> ch[-1]
‘ r ‘
>>> ch[-5]
‘ 1’

Note that while accessing individual elements, if you give an index outside the legal indices, Python will raise IndexError as shown below:
> > > ch [ 5 ]
Consider the following examples and write outputs:
Traceback (most recent call last):
File “<pyshell#5>”, line 1, in <module> ch [5]
IndexError: list index out of range

  • Accessing elements in a list is called indexing.

Let’s Try

Consider the following examples to understand indexing in a better way:

# positive indexing
>>> List = [ 10 , 20 , 30 , 40 , 50 ]
>>> print ( List )
[ 10 , 20 , 30 , 40 , 50]
>>> List [ 0 ]
10
>>> List [ 1 ]
20
>>> List [ 2 ]
30
>>> List [ 3 ]
40
>>> List [ 4 ]
50
# Negative indexing
>>> List = [ 10 , 20 , 30 , 40 , 50 ]
>>> print (List)
[ 10 , 20 , 30 , 40 , 50 ]
>>> List [-1]
50
>>> List [-2]
40
>>> List [-3]
30
>>> List [-4]
20
>>> List [-5]
10

Consider the following examples and write outputs:

>>> List= [ ” first ” , ” second ” ,  ” third ” ]
>>> List [ 0 ]
>>> List [ 1 ]
>>> List [ -1 ]
>>> List [ -3 ]
>>> my_list = [ ‘ n ‘ j ‘ o ‘ j ‘ t ‘ h ‘ e ‘ ]
>>> print (my_list [ 0 ] )
>>> print (my_list [ -4 ] )
>>> print (my_list [ 3 ] )
>>> print (my_list [ -1 ] )

Slicing

You know that a slice of a list is its sub-list. Just as you use indexing to access individual elements, you can use slicing to access a range of elements. You do this by using two indices, separated by a colon (:). Slicing is very useful for extracting parts of a sequence. The numbering here is very important. The first index is the number of the first element you want to include.

List slicing is an operation that extracts certain elements from a list and forms them into another list, possibly with a different number of indices and different index ranges. Slices are treated as boundaries, and the result will include all the elements between boundaries. The syntax for list slicing is as follows:
seq = L [start: stop: step]
The start, stop, step parts of the syntax are integers. Each of them is optional. They can be both positive and negative. If you omit the first index, the slice starts from 0, and omitting the stop will take it to the end. The default value of the step is 1.
You supply two indices as limits for your slice, where the first is included and the second is excluded.
Consider the following:
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[3:6]
[4, 5, 6]
>>> numbers [0:1]
[1]

Let’s say you want to access the last three elements of the list.
>>> numbers[7:10]
[8, 9, 10]
Now, index 10 refers to element 11 which does not exist but is one step after the last element you want.

In a regular slice, the step size is one, which means that the slice moves from one element to the next, returning all the elements between the start and end:
>>> numbers[0:10:1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In the above example, you can see that the slice includes another number, the step size, made explicit.
If the step size is set to a number greater than one, elements will be skipped accordingly. For example, a step size of two will include only alternate elements of the list between the start and the end:
>>> numbers[0:10:2]
[1, 3, 5, 7, 9]
numbers[3:6:3]
[4]
You can use the shortcuts, for example, if you want every fourth element of a sequence, you need to supply only a step size of four:
>>> numbers[::4]
[1, 5, 9]
The step size cannot be zero as that would not get you anywhere. However, it can be negative, which means extracting the elements from right to left:
>>> numbers [8:3:-1]
[9, 8, 7, 6, 5]
>>> numbers[10:0:-2]
[10, 8, 6, 4, 2]
>>> numbers [0:10:-2]
[ ]
>>> numbers[::-2]
[10, 8, 6, 4, 2]
>>> numbers [5::-2]
[6, 4, 2]
>>> numbers [:5:-2]
[10, 8]

  • A negative index means .traversal from the end of the list.

As you can see, the first limit (the leftmost) is still included, while the second (the rightmost) is excluded. While using a negative step size, you need to have the first limit (start index) higher than the second one.

  • Accessing parts of segments are called slicing.

Let’s Try

Consider the following examples to understand slicing in a better way:

>>> list_x = [ 1 , 2 , 3 , 4 , 5 ]
>>> list_y = list_x [ 2 : 5 ]
>>> print (list_y)
[ 3 , 4 , 5 ]
>>> print (list_x)
[ 1 , 2 , 3 , 4 , 5 ]
>>> x = [ 1 , 2 , 3 , 4 ]
>>> x [ 0 : 2 ]
[ 1 , 2 ]
>>> x [ 1 : 4 ]
[ 2 , 3 , 4 ]
>>> x [ 0 : -1 ]
[ 1 , 2 , 3 ]

Consider the following examples and write outputs:

n = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
print ( n [ 1 :5] )
print ( n [ : 5 ] )
print ( n [ 1 : ] )
print ( n [ : ] )
ind = [ ‘ Zero ‘ , ‘ one ‘ , ‘ two ‘ , ‘ three ‘ , ‘ four ‘ , ‘ five ‘ ]
print ( ind [ 2 : 4 ] )
print ( ind [ : 4 ] )
print ( ind [ 4 : ] )
print ( ind [ : ] )

Traversing

The sequential accessing of each element in a list is called traversing. This can be done by using either for or while loop statements. This can be done in two as shown in the following examples:
Using ‘in’ operator inside for loop
‘in’ operator using for loop Iterates each element of a list in sequence. For example:

for x in [1,2,3]:
print (x)

>>>
1
2
3
>>>

You can also use for/into work on a string. The string acts like a list of its chars, prints all the chars in a string. For example,

str=”Hello”
for ch in str:
print(ch)
>>>
H
e
1
1
o
>>>
for ch in [ ‘ p ‘ , ‘ y ‘ , ‘ t ‘ , ‘ h ‘ , ‘ o ‘ , ‘ n ‘ ]:
print (ch)
>>>
P
y
t
h
o
n
>>>

Note that each letter is accessed and displayed on a new line till all the elements are traversed and dis-played.
The in construct on its own is an easy way to test if an element appears in a list or not.
Rainbow = [ ‘ Red ‘ , ‘ Orange ‘ , ‘ Yellow ‘ , ‘ Green ‘ , ‘ Blue ‘ , ‘ Indigo ‘ , ‘ Violet ‘ ]
if ‘Orange’ in Rainbow:
print( ” Yes ” )
>>>
Yes
>>>

Let’s Try

Consider the following examples to understand tra-versing in a better way:

for Rainbow in [ ‘ Red ‘ , ‘ Orange ‘ , ‘ Yellow ‘ , let ‘ ]: ‘ Green ‘ , ‘ Blue ‘ , ‘ Indigo ‘ , ‘ Violet ‘ ] :
print ( ” I like ” , Rainbow )
>>>
I like Red
I like Orange
I like Yellow
I like Green
I like Blue
I like Indigo
I like Violet
>>>
namelist = [ ‘ Aman ‘ , ‘ Beena ‘ , ‘ Deepak ‘ ]
for x in namelist:
print ( ” Hello ” , x )>>>
Hello Aman
Hello Beena
Hello Deepak
>>>

Consider the following examples and write outputs:

for fruit in
[‘apple’,’banana’,’mango’ ] :
print(“I like”,fruit)
squares = [1, 4, 9, 16, 25]
sum = 0
for num in squares:
sum += num
print (sum)

Using range ( ) function

The range() gives a sequence of numbers in between the two integers given to it. The combination of the for-loop and the range ( ) function allows you to build a traditional numeric for loop:

# print the numbers from 0 through 10
for i in range(11):
print(i)
>>>
0
1
2
3
4
5
6
7
8
9
10
>>>
You can convert it to a list by using listQ. Let’s make it clear by following examples:
print ( list ( range ( 1 , 5 ) ) )
print ( list ( range ( 10 ) ) )
print ( list ( range ( 1 , 11 ) ) )
print ( list ( range ( 0 ) ) )
print ( list ( range ( 1 , 10 , 2 ) ) )
print ( list ( range ( 2 , 12 , 2 ) ) )
>>>
[ 1 , 2 , 3 , 4 ]
[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
[ ]
[ 1 , 3 , 5 , 7 , 9 ]
[ 2 , 4 , 6 , 8 , 10 ]
>>>

Note that range( 1 , 5 ) includes 1 but not 5 and range ( 1 , 10 , 2 ) will create a sequence of numbers but with a step of 2.
len ( ) is an useful function which you use on a list. it gives us the length ( number of elements ) of a list.
For example:

# Use of len() on a list
a = list ( range ( 1 , 5 ) )
print ( a )
print ( len ( a ) )
b = [12,23,27,33]
print(b)
print ( len ( b ) )

>>>
[1, 2, 3, 4]
4
[12, 23, 27, 33]
4
>>>
More examples of list traversal are discussed below:

Example
List traverse using while loop.

# List traversing
numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
i = 0
while i < 10:
print (numbers [i], end = ” ” )
i = i + 1RUN
>>>
1 2 3 4 5 6 7 8 9 10
>>>

Example
Traversing list using for loop

# Traversing list using for loop
numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
for i in numbers:
print ( i , end = ” ” )RUN
>>>
1 2 3 4 5 6 7 8 9 10
>>>

Example
Traversing list using while loop and len( ) function.

# Traversing list using while loop and len() function
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
i = 0
while i < len(numbers):
print(numbers[i],end =” “)
i += 1RUN
>>>
1 2 3 4 5 6 7 8 9 10
>>>

Example
Traversing list and Printing even numbers.

# Traversing list and printing even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
i = 1
while i < len(numbers):
print(numbers[i],end =” “)
i += 2RUN
>>>
2 4 6 8 10
>>>
  • Note that len ( ) is a built-in function, so you do not need to import it.

Example
Program to print elements of list along with their indices.

Program to print elements of a list with their positive and negative indices.

# Program to print elements of list along with their indices
ch = [ ‘ 1 ‘ , ‘ o ‘ , ‘ w ‘ , ‘ e ‘ , ‘ r ‘ ]
length = len(ch)
for i in range(length):
print(“At positive index”, i, “and negative index”, (i-length), “element is : “, ch [i])RUN
>>>
A positive index 0 and negative index -5 element is 1
A positive index 1 and negative index -4 element is o
A positive index 2 and negative index -3 element is w
A positive index 3 and negative index -2 element is e
A positive index 4 and negative index -1 element is r
>>>

Example
Program to find sum of the elements in a list.

# To find sum of the elements in a list
a = [10,20,30,40]
s = 0
i = 0
while (i<len(a)):
s = s+a[i]
i=i+1
print(“sum: ” , s )RUN
>>>
sum: 100
>>>

Example
Program to display the total and the average value of the elements in the list.

# To display total and the average value of the elements in the list.
list = [ 93 , 79 , 73 , 56 , 59 ]
total = 0
i = 0
while i < len ( list ):
total = total + list[i]
i = i + 1
average = total / len(list)
print(“Total: “, total)
print(“Average: “, average)RUN
>>>
Total: 360
Average: 72.0
>>>

Leave a Reply

Your email address will not be published. Required fields are marked *