Read more
Programming in Python
In Python, programs can be written in two ways namely Interactive mode and Script mode. The Interactive mode allows us to write codes in Python command prompt (>>>) whereas in script mode programs can be written and stored as separate file with the extension .py and executed. Script mode is used to create and edit python source file.
Accessing List elements
Example:
Marks = [10, 23, 41, 75]
Marks 10 23 41 75
Index (Positive) 0 1 2 3
IndexNegative) -4 -3 -2 -1
Positive value of index counts from the beginning of the list and negative value means counting backward from end of the list (i.e. in reverse order).
Syntax:
List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])
Example:
>>> Marks = [10, 23, 41, 75]
>>> print (Marks[0])
10
In the above example, print command prints 10 as output, as the index of 10 is zero
Accessing all elements of a list
Loops are used to access all elements from a list. The initial value of the loop must be
zero. Zero is the beginning index value of a list.
Example:
Marks = [10, 23, 41, 75]
i = 0
while i < 4:
print (Marks[i])
i = i + 1
Output :
10
23
41
75
In the above example, Marks list contains four integer elements i.e., 10, 23, 41, 75. Each element has an index value from 0. The index value of the elements are 0, 1, 2, 3 respectively. Here, the while loop is used to read all the elements. The initial value of the loop is zero, and the test condition is i < 4, as long as the test condition is true, the loop executes and prints the corresponding output
During the first iteration, the value of i is zero, where the condition is true. Now, the following statement print (Marks [i]) gets executed and prints the value of Marks [0] element ie. 10.
The next statement i = i + 1 increments the value of i from 0 to 1. Now, the flow of control shifts to the while statement for checking the test condition. The process repeats to print the remaining elements of Marks list until the test condition of while loop becomes false
Reverse Indexing
Python enables reverse or negative indexing for the list elements. Thus, python lists index in opposite order. The python sets -1 as the index value for the last element in list and -2 for the preceding element and so on. This is called as Reverse Indexing
0 Reviews