List in Python

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

1. len()

It will return how many elements are there in the list.

2. in

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.

  1. element -> element you want to search.
  2. beg -> from which index you want to start searching.
  3. end -> till which index you want to start searching.

beg and end parameters are optional.

4. count()

It will count the occurrence of the provided no. of value.

How to add elements in the list?

5. append()

It will append that element at the end of the list In [12]:

6. insert(position, element)

7. extend(list)

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?

8. pop(n)

It will pop the element from that index. It is an optional argument, if not mentioned that it will pop from the end. In [17]:

9 del[a:b]

It will delete the elements in a range, excluding the end index.

10. remove()

This function is used to delete the first occurrence of the number mentioned in its arguments.

11. clear()

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.

12. reverse()

It will reverse the whole list.


Close Menu