Accessing elements from the List
M3-R5.1 · Chapter 5: Sequence Data Types · 8 min read
Accessing elements from the List: In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. The index must be an integer. Nested lists are accessed using nested indexing.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes.
Ø List-name [start: end] will give you elements between indices start to end-1.
Ø The first item in the list has the index zero (0)
>>> number[2]
87
>>> number[-1]
27
>>> number[-8]
12
>>> number[8]
IndexError: list index out of range
>>> number[5]=55 #Assigning a value at the specified index
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]
Example: Accessing elements from list
List = ["Python", "With", "J.P.Mishra"]
print("Accessing a element from the list")
print(List[0])
print(List[2])
Add Elements to a Python List:
We use the append () method to add an element to the end of a Python list.
Example:
fruits = ['apple', 'banana', 'orange']
print('Original List:', fruits)
fruits. append('cherry') # using append method
print('Updated List:', fruits)
Change List Items : We can change the items of a list by assigning new values using the = operator.
Example:
colors = ['Red', 'Black', 'Green']
print('Original List:', colors)
colors[2] = 'Blue'
print('Updated List:', colors)
Remove an Item From a List : We can remove an item from a list using the remove() method.
Example:
numbers = [2,4,7,9]
numbers.remove(4) # remove 4 from the list
print(numbers)
Python List Length : We can use the built-in len() function to find the number of elements in a list.
Example:
cars = ['BMW', 'Mercedes', 'Tesla']
print('Total Elements: ', len(cars))
Iterating Through a List : We can use a for loop to iterate over the elements of a list.
Example:
fruits = ['apple', 'banana', 'orange']
for i in fruits:
print(i)
Traversing a LIST: Traversing means accessing and processing each element.
Method-1:
>>> day=list(input("Enter elements :"))
Enter elements : sunday
>>> for d in day:
print(d)
Examples:
|
List Traverse using While loop L1=[10,21,30,41,50,61,70,81,90,101] i=0 while(i<10): print (L1[i],end=",") i=i+1 |
List Traverse using For loop L1=[10,21,30,41,50,61,70,81,90,101] for i in L1: print (i,end=",") |
|
List Traverse using While loop and len() function L1=[10,21,30,41,50,61,70,81,90,101] i=0 while(i<len(L1)): print (L1[i],end=",") i=i+1 |
Traverse a list and print even number L1=[10,21,30,41,50,61,70,81,90,101] i=0 while(i<len(L1)): print (L1[i],end=",") i=i+2 |
|
Print the element of list along with their indecs L1=["P","R","A","K","A","S","H"] length=len(L1) for i in range (length): print ("At positive index",i,"element is",L1[i]) |
Find the sum of element in a list L1=[10,20,30,40,50] sum=0 i=0 while(i<len(L1)): sum=sum+L1[i] i=i+1 print ("sum of all element=",sum) |
|
Program to display total and the average value of the elements in the list L1=[10,20,30,40,50] tot=0 i=0 while(i<len(L1)): tot=tot+L1[i] i=i+1 avg=tot/len(L1) print ("Total of all element=",tot) print ("Average of all element=",avg) |
List Operators:
Ø Joining operator +
Ø Repetition operator *
Ø Slice operator [ : ]
Ø Comparison Operator <, <=, >, >=, ==, !=
Joining Operator: It joins two or more lists.
Example:
|
>>> L1=['a',56,7.8] >>> L2=['b','&',6] >>> L3=[67,'f','p'] >>> list=L1+L2+L3 >>> list ['a', 56, 7.8, 'b', '&', 6, 67, 'f', 'p'] |
CONCATENATION # list1 is a list of the First Five odd integers >>> list1=[1,3,5,7,9] # list2 is a list of the First Five even integers >>> list2=[2,4,6,8,10] # Elements of list1 followed by list2 >>> list1+list2 OUTPUT: [1,3,5,7,9, 2,4,6,8,10] |
Repetition Operator: It replicates a list specified number of times.
Example:
|
>>> L1*3 ['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8] >>> 3*L1 ['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8] |
>>> list1=[“Hello”] # Element of list1 Repeated 5 Times >>> >>>list1 * 5 OUTPUT: [“ Hello”, “ Hello”, “Hello”, “Hello”, “Hello”] |
MENBERSHIP
>>> list1[ “ Varun ”, “ Ravindra ”, “ Amrit ”]
>>> “Amrit” in list1 OUTPUT: True
>>> “Nitin” in list1 OUTPUT: False
Slice Operator:
Syntax:
List-name [start:end] will give you elements between indices start to end-1.
#Initializes a list list1
>>> list1=[ ”Varun”, ”Ravindra”, ”Amrit”, ”Nitin”, ”Rahul”, ”Prajwal” ]
>>> list1[2:4]
OUTPUT: [”Amrit”, ”Nitin”]
>>> num=[12,56,87,45,23,97,56,27]
>>> num[2:-2]
OUTPUT: [87, 45, 23, 97]
#PRACTICE MORE
>>> list1[ start: stop ] # items start through stop-1
>>> list1[ start: ] # items start through the rest of the array
>>> list1[: Stop] # items From the beginning Through stop-1
>>> list1[: ] # A Copy of the Whole list
>>> list1[-1 ] # last item in the list
>>> list1[-2: ] # last 2 item in the list
>>> list1[:-2 ] # Everything except the last 2 item in the list
>>> list1[ : :-1 ] # all item in the List in Reverse order
>>> list1[ 1 : :-1 ] # The first Two item in the List in Reverse order
>>> list1[ : -3:-1 ] # The Last Two item in the List in Reverse order
>>> list1[ -3: : -1 ] # Every Thing Except Last Two item in the List in Reverse order
Comparison Operators:
- Compares two lists
- Python internally compares individual elements of lists in lexicographical order.
- It compares the each corresponding element must compare equal and two sequences must be of the same type.
- For non-equal comparison as soon as it gets a result in terms of True/False, from corresponding elements’ comparison. If Corresponding elements are equal, it goes to the next element and so on, until it finds elements that differ.
Example:
>>>L1, L2 = [7, 6, 9], [7, 6, 9]
>>>L3 = [7, [6, 9] ]
For Equal Comparison:
|
Comparison |
Result |
Reason |
|
>>>L1==L2 |
True |
Corresponding elements have same value and same type |
|
>>>L1==L3 |
False |
Corresponding values are not same |
For Non-equal comparison:
|
Comparison |
Result |
Reason |
|
>>> L1>L2 |
False |
All elements are equal |
|
>>> L2>L3 |
TypeError: '>' not supported between instances of 'int' and 'list' |
in L2, element at the index 1 is int type and in L3 element at the index 1 is list type |
|
>>>[3,4,7,8]<[5,1] |
True |
3<5 is True |
|
>>>[3,4,7,8]<[3,4,9,2] |
True |
First two elements are same so move to next element and 7<9 is True |
|
>>>[3,4,7,8]<[3,4,9,11] |
True |
7<9 is True |
|
>>>[3,4,7,8]<[3,4,7,5] |
False |
8<5 is False |