Lists are used to store multiple items in a single variable. A list is created by placing all the items (elements) inside square brackets [], separated by commas. It can have any number of items and they may be of different types (integer, float, string etc.).

Examples of Lists

There are different types of lists in python. Such as integer lists, floating lists, string lists and mixed lists. In the following ways we can create different types of lists in Python.

Integer Lists

Floating Lists

String Lists

Mixed Lists

Creating empty lists

We can also create empty list in two ways as follows.

List Items

List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc. Since lists are indexed, lists can have items with the same value.

Access elements from a list

We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.

List Length

To determine how many items a list has, use the len() function.

Updating item in a list

We can update any item of a list as given in the following way.

Adding new items in the list

We can add new items in a list as explain in the following example.

Adding more items at the same time

Adding element at specific position

We can also add elements in a list at some particular position in the following way.

Concatenating Two Lists

We can also merge two or more lists together.

Getting Index of a particular item

We can easily find the index number of a particular item in a list as follows.

Removing Element from list

We can also remove element from the list in the following way.

Sorting elements of lists

We can also perform sorting on the elements of lists by using sort() function.

Reversing elements of a lists

We can also reverse the elements of lists.

Removing last item from lists

Remove Specified Index

The pop() method removes the specified index.

The del keyword also removes the specified index.

Clear the List

The clear() method empties the list. The list still remains, but it has no content.

Accessing list elements using negative index

We can also access the elements of lists using negative index which is not allowed in any other programming language.

One Reply to “List in Python”

Leave a Reply

Your email address will not be published. Required fields are marked *