In this blog, we will look at various functions of list how to access, add elements, removing, etc. The list is like an array if you studied in some other programming languages may be. In Python it is mutable.
The mutable and immutable concept is been discussed during a string data type. Hope you are clear with that.
Let’s get started to check different methods of it.
How to create a list and accessing it.
Properties of List
List are heterogeneous in nature. It means it can contain different types of element. All elements of lists are not necessary to be of the same data type.
Lists are mutable. Mutable means change after creation. Let’s see with the example below i.e, on changing the value of l1 at index 0, l2 also gets modified as it is pointing to the same memory location as l1.
Methods of list
It will return how many elements are there in the list.
Actually, it is an operator basically, which will check if this element is present in the list or not. “in” can also be used for printing values in a loop
3. index(element, beg, end)
It will return the index of the searched element. It takes 3 parameters.
- element -> element you want to search.
- beg -> from which index you want to start searching.
- end -> till which index you want to start searching.
beg and end parameters are optional.
It will count the occurrence of the provided no. of value.
How to add elements in the list?
It will append that element at the end of the list In :
6. insert(position, element)
This function is used to extend the list with the elements present in another list. This function takes another list as its argument.
How to delete elements from the list?
It will pop the element from that index. It is an optional argument, if not mentioned that it will pop from the end. In :
It will delete the elements in a range, excluding the end index.
This function is used to delete the first occurrence of the number mentioned in its arguments.
It will make the whole list empty.
How to sort and reverse the list?
11. sort() and sorted()
It will sort the list in increasing order, only for integers not string.
There is a difference between sort() and sorted(), the sort will make changes in the exact location/memory but sorted() will sort only for that time and will not replicate in memory.
In short, we have one more parameter, reverse. If reverse = True, then it will sort in descending order.
It will reverse the whole list.