Python Lists

A list is similar to an array that consists of a group of elements or items. Just like an array, a list can store elements. But, there is one major difference between an array and a list. An array can store only one type of elements whereas a list can store different types of elements. Hence lists are more versatile and useful than an array. Perhaps lists are the most used data type in Python programs.

The list appears as given below:

[10, 'Digi Brains Academy', 'M', 50, 55, 62, 74, 66]

Indexing and slicing operations are commonly done on lists. Indexing represents accessing elements by their position numbers in the list. The position numbers start from 0 onwards and are written inside square braces.

Program: A Python program to create lists with different types of elements.

Creating Lists using range() Function:

We can use range() function to generate a sequence of integers which can be stored in a list. The format of the range() function is:

range(start, stop, stepsize)

If we do not mention the 'start', it is assumed to be 0 and the 'stepsize' is taken as 1.

A Python program to create lists using range() function.

Updating the Elements of a List

Lists are mutable. It means we can modify the contents of a list. We can append, update or delete the elements of a list depending upon our requirements.
Appending an element means adding an element at the end of the list.
To append a new element to the list, we should use the append() method.

Updating an element means changing the value of the element in the list. This can be done by accessing the specific element using indexing or slicing and assigning a new value. Consider the following statements:

Deleting an element from the list can be done using 'del' statement. The del statement takes the position number of the element to be deleted.

We can also delete an element using the remove() method. In this method, we should pass the element to be deleted.
lst.remove(11) #delete 11 from lst
Let's write a program to retrieve the elements of a list in reverse order. This can be done easily by using the reverse() method, as:

This will reverse the order of elements in the list and the reversed elements are available in the list.