In python List is one of the important data structutres. A list allows us to store multiple values in a single variable.
1.len()-Find the number of elements.
the len() function return the total number of elements in a list.
fruits = ["apple","banana","orange","mango"] print(len(fruits)) _Output:_ 4 Here the list contain four elements,so len() returns 4.
2.append()-Add an Element
The append() method adds a new element at the end of a list.
fruits = ["apple","banana","orange"] fruits.append("mango") print(fruits) _Output:_ ['apple','banana','Orange','mango'] The new element "mango" is added to the end.
3.count()-Count Occurences
The count() method returns how many times a particular element in a list.
numbers=[10,20,30,20,40,20] print(numbers.count(20)) _Output:_ 3 The number 20 appears three times in a list.
4.index()-Find the positon of an element.
fruits = ["apple", "banana", "orange", "mango"] print(fruits.index("orange")) _Output:_ 2 Remember python list indexing starts from zero.
it the element is not present index() raises a ValueError.
5.remove() - Remove an Element
The remove() method remove the first occurence of a specified element.
fruits = ["apple","banana","orange","banana"] fruits.remove("banana") print(fruits) _Output:_ ['apple','orange','banana'] Only the first occurence of banana is removed.
6.insert()-Add an Element at a Specific Position.
The insert() method adds an element at the specified index.
Syntax:
list.insert(index,element)
Example:
numbers = [10,20,30,40] numbers.insert(2,99) print(numbers) _Output:_ [10,20,99,40] 99 is inserted at index 2.The existing elements shifts to right.
Name Type Purpose
len() Built-in-function Return the number of elements.
append() List method Adds an element at the end.
count() List method Counts occurences.
index() List method Finds the first matching element index
remove() List method Removes the first matching element
insert() List method Inserts an element at a specify position