Lists in Python
Lists in Python
List Slicing
• Just like strings, values in a list can be accessed by using their index or indices.
• You can update a single or multiple element in a list by giving the index on the left
side of the assignment operator.
• To remove a particular list element, you can use the del statement.
Slicing List
Slicing operation Explanation
L1[3] It accesses the fourth element in the list.
L1[2:5] It accesses elements starting from the second index to fourth index.
L1[1:-2] It accesses elements starting from the first index upto the -3 index.
L1[ :4] It omits the first index to start accessing elements from the beginning
upto the third index.
L1[2: ] It omits the last index to start accessing elements from the second
index to the end.
L1[1] = 90 It updates the element present at index 1.
del L1[3] It removes the element present at index 3.
List slicing
Function Description
len(L1) It returns the number of elements in the list.
max(L1) It returns the item from the list with maximum value.
min(L1) It returns the item from the list with minimum value.
sum(L1) It returns the sum of all the elements in the list.
tuple(L1) It converts the list into a tuple.
List Methods
Python includes the following list methods:
list.append(obj) The method appends object obj to the end of the list.
list.count(obj) It returns a count of how many times an object obj occurs in the list.
list.extend(seq) It appends the content of seq to the list..
list.index(obj) It returns the lowest index in the list where obj appears.
list.insert(index,obj) This function inserts the object obj into the list at the particular index.
list.pop( ) This method is used to remove and return the last object from the list .
list.remove(obj) It removes the first instance of the object obj from the list .
Practice Time
Write a Python script to create a list of numbers and display the count of numbers,
maximum, minimum, sum and average of numbers in the list.
a. Consider a list with name Test, contains 10 elements. You can access 4th element from the
test using
i. test[4] ii. Test[5] iii. Test[3] iv. Test[2]