Lists in Python

Posted by

Python Lists are used to store multiple items in a single variable. We create a list using an angle bracket “[]” and separated it by commas.

The list is mutable, which means it may be altered or updated after it is created.

Example of a List in Python:

Here is an example of a Python List using the angle bracket “[]”.

Output:

Accessing Python List Elements

Getting the value of an element in a list is as simple as using the index in the list. Indexes are assigned from 0 in Python. We can also access items with negative indexes in Python. Negative indexes indicate entries counted from the list’s end.

Output:

Concatenation and Replication of Lists in Python

List concatenation is the process of combining the contents of two lists into one.

Output:

List replication is the process of copying the contents of a list a finite number of times into the same or another list.

Output:

Adding Items to Lists

We can use the insert function to add an item to a specific index of a list. It takes two arguments the first argument will be the index and the second argument will be the item.

Output:

Using the append function, we can append an element to the end of a list.

Output:

Delete or Remove items from Lists

We can remove a specific item from a list using the del keyword.

Output: Rahul will be removed from the name1 list.

You can also remove the list item by passing the item name as an argument into the remove keyword.

Looping/Iterating through Lists

The following example shows how to iterate over all of the items in a list.

Output:

Python List Sorting

We use the sort() method to arrange the items on the list in a specific order. It sorts the items in ascending order by default.

Output:

We can sort in descending order using reverse argument in the sort function.

Output:

Reverse List in Python

reverse() : This reverses the order of list elements in python.

Output:

Stack

The two operations in Python allow for the intuitive usage of lists as a stack.

  1. append()
  2. pop().

Leave a Reply

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