Introduction
A list is an in-built Python data structure that can be changed. It is an ordered and changeable collection of elements. By ordered sequence, it is meant that every element of the list can be called individually by its index number.
Some of the important points about the list are:
- The list can be created by placing all elements inside a square bracket [].
- All elements inside the list must be separated by a comma “,”.
- It can have any number of elements and the elements need not be of the same type. So, we can also say that it is a collection of heterogeneous data types.
- Lists index always starts from 0, so if the length of a string is “n”, then the last element will have an index of n-1.
- Lists are mutable therefore they can be modified after creation.
- An Empty List is denoted as L[ ].
LIST METHODS
Let us understand each method.
INDEX
This method returns the index of the specified elements. It takes one argument. If the element specified is not present, it generates an error.
- l= [7,4,2,6,9,1,5]
- a= l.index(9)
- print(“Number found at”,a)
The output of the following code is shown below.
It returns the index of the first and only occurrence of specified element. If you want to specify a range of valid index, you can indicate the start and stop indices.
- l= [7,4,9,2,6,9,1,5,4,9]
- a= l.index(9)
- print(“Number found at”,a)
APPEND
This method is used for appending and adding elements to the List. It is used to add elements to the last position of List. It takes only one argument so it can append only one element at a time.
- l= [7,4,2,6,9,1,5]
- a= l.append(14)
Adding multiple elements cannot be done through Append(). Like, see the below output,
EXTEND
If we want to append several objects contained in a list, we use Extend(). This method adds multiple items but it should be in the form of a list.
- l=[7,4,2,6,9,1,5]
- a= l.append(3,8)
- a= l.extend(3,8)
- a= l.extend([3,8])
See the output.
This allows you to join two lists. The sequence represented by the object sequence is extended to the list; i.e, takes in a second list as its argument.
Summary
In this article, we discussed some basic concepts and a few methods of List. I hope this will help the readers to understand how to use and implement Lists in Python. In my next article, I will explain the remaining methods of Lists.
Feedback or queries related to this article are most welcome. Thanks for reading.