Page 312 - AI Ver 1.0 Class 9
P. 312
Creating a list of students with roll no students = [21, "Gunjan", 94.5, 34, "Rohit",
and percentage (list of mixed values) 91.3]
Creating a list within another list section = ["A", 25, "English", ["B",34], ["C",37],
56.7]
Creating a list with repeated values L1 = [10] * 5 # L1 will have [10, 10, 10, 10,
10]
Creating a list from another sequence alpha = list("hello") #string converted to a
or string using list( ) function list #output will [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
Values input from the user in a list L1 = list(input("enter numbers :"))
Accessing the Elements of a List
The elements of a list can be accessed by using its index number starts with 0 (zero). There are two different
ways of using the index number:
• Forward Indexing: The index number begins with 0 till length-1 and we refer the elements from left to right.
• Negative/Backward Indexing: The index number begins with -1 till -length and we refer the elements from
right to left. For example,
L1 = ['P', 'Y', 'T', 'H', 'O', 'N']
Forward Indexing 0 1 2 3 4 5
P Y T H O N
–6 –5 –4 –3 –2 –1 Backward Indexing
Each element can be accessed by using:
listname[index number]
Commands Output
print(L1[0]) P
print(L1[3]) H
print(L1[-3]) H
print(L1[-1]) N
print(L1) #print complete list ['P', 'Y', 'T', 'H', 'O', 'N']
print(L1[0], L1[4]) P O
Traversing a List
Traversing means visiting each element and processing it as required by a program. We use a loop to traverse a
list. There are different ways of visit each element as shown below:
Commands Output
L1=['P', 'Y', 'T', 'H', 'O', 'N'] P ! Y ! T ! H ! O ! N !
for eachvalue in L1:
print(eachvalue, end="!")
310 Touchpad Artificial Intelligence-IX

