Nearby lessons

64 of 159

Python - Lists

📌 What You Will Learn
  • Understand what a list is and how to create one
  • Access list items with positive and negative indexes and slicing
  • Add and remove items with append(), insert(), extend(), remove(), pop() and clear()
  • Order lists with sort(), sorted() and reverse()
  • Iterate over lists with for and while loops
  • Apply nested lists and list comprehensions

Introduction

If we want to represent a group of individual objects as a single entity, where insertion order is preserved and duplicate objects are allowed, then we should use a List.

A list is one of the most commonly used data structures in Python.

It can store multiple values in a single variable and allows different types of data to be stored together.

Characteristics of List

A Python list has the following characteristics:

  • Insertion order is preserved.
  • Duplicate objects are allowed.
  • Heterogeneous objects are allowed.
  • List is dynamic.
  • List objects are mutable.

Features of List

1. Insertion Order is Preserved

The elements are stored in the same order in which they are inserted.

2. Duplicate Objects are Allowed

A list can contain duplicate values.

3. Heterogeneous Objects are Allowed

A list can store different types of data together.

Example:

Example - Heterogeneous List

Loading editor…

Explanation

The above list contains:

  • Integer values
  • String values
  • Duplicate value (10)

More Features of List

4. List is Dynamic

A list is growable.

Based on our requirement, we can increase or decrease its size.

5. List is Mutable

List objects are mutable.

This means we can modify the contents of a list after creating it.

Representation of List

List elements are enclosed within square brackets [].

Each element is separated by a comma (,).

Syntax

Loading editor…

Index in List

Python uses indexes to access list elements.

Indexes also help us differentiate duplicate elements.

Python supports two types of indexing:

  • Positive Index
  • Negative Index

Positive and Negative Index

Positive Index Negative Index
Starts from left to right. Starts from right to left.
First index is 0. Last index is -1.

Example - List Index

Element 10 A B 20 30 10
Positive Index 0 1 2 3 4 5
Negative Index -6 -5 -4 -3 -2 -1
Loading editor…

Creating List Objects

There are different ways to create a list in Python.

Method 1 - Create an Empty List

Loading editor…

Method 2 - Create a List with Known Elements

Loading editor…

Method 3 - Using list() Function

Loading editor…

Method 4 - Using split() Method

The split() method returns a list.

Example - split()

Loading editor…

Accessing List Elements

List elements can be accessed in two ways:

  1. Using Index
  2. Using Slice Operator

Python supports both positive and negative indexing.

Example - Positive Index

Loading editor…

Example - Negative Index

Loading editor…

Accessing Elements Using Slice Operator

The slice operator is used to access multiple elements from a list.

Example 1 - Slice Operator

Loading editor…

Example 2 - Complete List

Loading editor…

Traversing a List

Traversing means accessing every element of a list one by one.

Python provides different ways to traverse a list.

The most commonly used methods are:

  • Using for loop
  • Using while loop

Traversing Using for Loop

The for loop is the easiest way to traverse a list.

It automatically reads one element at a time.

Example 1 - Print All List Elements

Loading editor…

Explanation

The for loop visits every element of the list.

Each element is stored in the variable x and printed.

Example 2 - Print Only Even Numbers

Loading editor…

Example 3 - Print Only Odd Numbers

Loading editor…

Example 4 - Print Squares of List Elements

Loading editor…

Traversing Using while Loop

We can also traverse a list using the while loop.

In this method, we use the index of each element.

Example 1 - Traverse Using while Loop

Loading editor…

Explanation

len(list) returns the total number of elements.

The variable i is used as the index.

The loop continues until all elements are printed.

Example 2 - Print List Elements in Reverse Order

Loading editor…

Positive and Negative Index Traversal

Every element in a list has both a positive index and a negative index.

We can display both indexes while traversing the list.

Example - Positive and Negative Index

Loading editor…

Mutable Nature of List

Lists are mutable.

This means we can change their contents after creation.

We can:

  • Modify existing elements.
  • Add new elements.
  • Delete existing elements.

Updating List Elements

We can update an element by using its index.

Example 1 - Update an Element

Loading editor…

Example 2 - Update First Element

Loading editor…

Example 3 - Update Last Element Using Negative Index

Loading editor…

Example 4 - Update Multiple Elements Using Slice

Loading editor…

Adding Elements to a List

Python provides several methods to add new elements to a list.

The most commonly used methods are:

  • append()
  • insert()
  • extend()

These methods allow us to add one or more elements to an existing list.

append() Method

The append() method adds a single element at the end of the list.

Syntax:

Syntax

Loading editor…

Example 1 - Add One Element

Loading editor…

Example 2 - Append Different Data Types

Loading editor…

Explanation

A list can store different types of objects.

The append() method always adds the new element at the end of the list.

Example 3 - Append User Input

Loading editor…

insert() Method

The insert() method inserts an element at a specified position.

Syntax:

Syntax

Loading editor…

Example 1 - Insert an Element

Loading editor…

Explanation

The element is inserted at the specified index.

Existing elements are automatically shifted to the right.

Example 2 - Insert at Beginning

Loading editor…

Example 3 - Insert at Last

Loading editor…

Important Notes

  • If the index is greater than the list size, the element is added at the end.
  • If the index is negative, Python inserts the element according to the negative index.

Example 4 - Index Greater Than List Size

Loading editor…

Example 5 - Negative Index

Loading editor…

extend() Method

The extend() method adds all elements from another iterable to the end of the list.

The iterable can be another list, tuple, set, or any iterable object.

Syntax:

Syntax

Loading editor…

Example 1 - Extend Using Another List

Loading editor…

Example 2 - Extend Using Tuple

Loading editor…

Example 3 - Extend Using String

Loading editor…

Explanation

A string is also an iterable.

Therefore, each character is added separately to the list.

Difference Between append() and extend()

append() extend()
Adds only one element. Adds multiple elements.
Accepts any object. Accepts only an iterable.
The object is added as a single element. Each element of the iterable is added separately.

Example - append() vs extend()

Loading editor…

Removing Elements from a List

Python provides different methods to remove elements from a list.

The most commonly used methods are:

  • remove()
  • pop()
  • clear()

Each method works differently depending on the requirement.

remove() Method

The remove() method removes the specified element from the list.

If duplicate values are present, only the first occurrence is removed.

Syntax:

Syntax

Loading editor…

Example 1 - Remove an Element

Loading editor…

Example 2 - Remove Duplicate Element

Loading editor…

Explanation

The remove() method deletes only the first matching element.

Other duplicate elements remain in the list.

Example 3 - Element Not Present

Loading editor…

pop() Method

The pop() method removes an element using its index.

It also returns the removed element.

Syntax:

Syntax

Loading editor…

Example 1 - Remove Last Element

Loading editor…

Explanation

If no index is specified, pop() removes the last element.

Example 2 - Remove Element at Index

Loading editor…

Example 3 - Invalid Index

Loading editor…

clear() Method

The clear() method removes all elements from the list.

After using clear(), the list becomes empty.

Syntax:

Syntax

Loading editor…

Example 1 - Remove All Elements

Loading editor…

Explanation

The list object still exists.

Only its elements are removed.

Example 2 - Check List After clear()

Loading editor…

Difference Between remove(), pop() and clear()

Method Description
remove() Removes an element by value.
pop() Removes an element by index and returns it.
clear() Removes all elements from the list.

Real World Usage

These methods are commonly used in:

  • Student management systems
  • Shopping cart applications
  • Employee record management
  • Task management applications
  • Data processing programs

del Statement

The del statement is used to delete elements or an entire list.

Unlike remove() and pop(), del is a Python keyword.

It can delete:

  • A single element
  • Multiple elements
  • A complete list object

Syntax

Loading editor…

Example 1 - Delete an Element

Loading editor…

Example 2 - Delete Multiple Elements

Loading editor…

Example 3 - Delete Entire List

Loading editor…

Explanation

After deleting the entire list, the variable no longer exists.

Trying to access it raises a NameError.

Difference Between del and clear()

del clear()
Deletes the list or selected elements. Removes all elements only.
The list variable can also be removed. The list variable still exists.
Raises NameError if the deleted list is accessed. Produces an empty list [].

Stack Data Structure

A Stack is a linear data structure.

It follows the LIFO (Last In, First Out) principle.

The element inserted last is removed first.

Python lists can be used to implement a stack.

Stack Operations

Operation Method
Push append()
Pop pop()

Example 1 - Push Operation

Loading editor…

Example 2 - Pop Operation

Loading editor…

Example 3 - Complete Stack Program

Loading editor…

Working of Stack

The last inserted element is always removed first.

This behavior is called LIFO (Last In, First Out).

Comparison of List Methods

Method Purpose
append() Add one element at the end.
extend() Add multiple elements.
insert() Insert an element at a specified position.
remove() Remove an element by value.
pop() Remove an element by index and return it.
clear() Remove all elements.
del Delete elements or the complete list.

List Information Functions

Python provides several built-in functions and methods to get information about a list.

The most commonly used list information functions are:

  • len()
  • count()
  • index()

These functions help us find the size of a list, count duplicate elements, and locate elements.

len() Function

The len() function returns the total number of elements present in a list.

Syntax:

Syntax

Loading editor…

Example 1 - Find Length of a List

Loading editor…

Example 2 - Length of an Empty List

Loading editor…

Example 3 - Length of a Heterogeneous List

Loading editor…

Explanation

The len() function counts every element in the list.

It does not depend on the data type of the elements.

count() Method

The count() method returns the number of occurrences of a specified element in the list.

Syntax:

Syntax

Loading editor…

Example 1 - Count Duplicate Elements

Loading editor…

Example 2 - Count String Elements

Loading editor…

Example 3 - Element Not Present

Loading editor…

Explanation

If the specified element is not available, the count() method returns 0.

index() Method

The index() method returns the index of the first occurrence of the specified element.

Syntax:

Syntax

Loading editor…

Example 1 - Find Index

Loading editor…

Example 2 - Duplicate Elements

Loading editor…

Explanation

If duplicate elements are present, the index() method returns the index of the first occurrence only.

Example 3 - Element Not Available

Loading editor…

Example 4 - Search from a Specific Index

Loading editor…

Explanation

The second argument specifies the starting index for the search.

The search begins from that position instead of the beginning of the list.

Example 5 - Search Within a Range

Loading editor…

Explanation

The third argument specifies the ending position.

The search is performed only within the given range.

Difference Between count() and index()

count() index()
Returns the number of occurrences. Returns the index of the first occurrence.
Returns 0 if the element is not present. Raises ValueError if the element is not present.
Used to count duplicate values. Used to locate an element.

Real World Usage

These functions are commonly used in:

  • Searching data
  • Finding duplicate records
  • Counting student attendance
  • Inventory management
  • Data validation

Ordering List Elements

Sometimes we need to arrange the elements of a list in a specific order.

Python provides the following methods for ordering list elements:

  • reverse()
  • sort()
  • sorted()

reverse() Method

The reverse() method reverses the order of elements in the original list.

It does not create a new list.

Syntax

Loading editor…

Example 1 - Reverse a List

Loading editor…

Explanation

The original list is modified.

The first element becomes the last element and the last element becomes the first element.

Example 2 - Reverse a String List

Loading editor…

sort() Method

The sort() method arranges list elements in ascending order by default.

It modifies the original list.

Syntax

Loading editor…

Example 1 - Sort Numbers

Loading editor…

Example 2 - Sort Strings

Loading editor…

Explanation

Strings are sorted in alphabetical order.

Numbers are sorted from smallest to largest.

Descending Order

To sort elements in descending order, use the reverse=True argument.

Syntax

Loading editor…

Example 1 - Descending Order

Loading editor…

Example 2 - Descending String Order

Loading editor…

Sorting Mixed Data Types

The sort() method cannot sort a list containing incompatible data types such as integers and strings together.

Example - Mixed Data Types

Loading editor…

sorted() Function

The sorted() function returns a new sorted list.

The original list remains unchanged.

Syntax

Loading editor…

Example 1 - Using sorted()

Loading editor…

Explanation

The sorted() function returns a new sorted list.

The original list is not modified.

Example 2 - Descending Order

Loading editor…

Difference Between reverse(), sort() and sorted()

Method / Function Description
reverse() Reverses the current order of the list.
sort() Sorts the original list.
sorted() Returns a new sorted list.

Real World Usage

Ordering methods are commonly used in:

  • Student result systems
  • Employee salary reports
  • Product price sorting
  • Leaderboard applications
  • Data analysis projects

List Operators

Python provides several operators that can be used with lists.

The most commonly used list operators are:

  • Concatenation Operator (+)
  • Repetition Operator (*)
  • Comparison Operators
  • Membership Operators

Concatenation Operator (+)

The + operator joins two or more lists.

It creates and returns a new list containing the elements of both lists.

Syntax

Loading editor…

Example 1 - Join Two Lists

Loading editor…

Example 2 - Join String Lists

Loading editor…

Important Notes - (+)

  • The original lists are not modified.
  • A new list is created.
  • Only list objects can be concatenated.

Example 3 - Invalid Concatenation

Loading editor…

Repetition Operator (*)

The * operator repeats the elements of a list.

The number specifies how many times the list should be repeated.

Syntax

Loading editor…

Example 1 - Repeat a List

Loading editor…

Example 2 - Repeat String List

Loading editor…

Explanation

The original list is not modified.

A new repeated list is returned.

Comparison Operators

Lists can be compared using comparison operators.

Python compares the elements one by one from left to right.

Supported Comparison Operators

Operator Description
==Equal to
!=Not equal to
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to

Example 1 - Equality Operator

Loading editor…

Example 2 - Not Equal Operator

Loading editor…

Example 3 - Greater Than Operator

Loading editor…

Explanation

Python compares list elements one by one.

The comparison stops as soon as a different element is found.

Membership Operators

Membership operators are used to check whether an element exists in a list.

Python provides two membership operators:

  • in
  • not in

Example 1 - in Operator

Loading editor…

Example 2 - not in Operator

Loading editor…

Explanation

The in operator returns True if the element exists.

The not in operator returns True if the element does not exist.

Difference Between + and * Operators

+ *
Joins two lists. Repeats list elements.
Requires two lists. Requires a list and an integer.
Creates a larger combined list. Creates repeated copies of the same list.

Nested List

A list can contain another list as its element.

Such a list is called a Nested List.

Nested lists are useful for representing tables, matrices, and two-dimensional data.

Example 1 - Nested List

Loading editor…

Understanding Nested List

Each element of the main list is itself another list.

Every inner list is called a row.

Individual elements can be accessed using two indexes.

Accessing Elements from Nested List

The first index selects the row.

The second index selects the column.

Example 2 - Access Nested Elements

Loading editor…

Traversing Nested List

Nested lists are usually traversed using nested loops.

The outer loop processes rows.

The inner loop processes the elements of each row.

Example 3 - Traverse Nested List

Loading editor…

Matrix Representation

A matrix is a collection of rows and columns.

In Python, a matrix can be represented using a nested list.

Example 4 - Matrix

Loading editor…

Example 5 - Matrix Elements

Loading editor…

List Comprehension

List Comprehension provides a short and simple way to create a list.

It reduces the number of lines of code.

It is commonly used with loops and conditions.

General Syntax

Loading editor…

Example 1 - Create a List

Loading editor…

Example 2 - Squares Using List Comprehension

Loading editor…

Example 3 - Even Numbers

Loading editor…

Example 4 - Odd Numbers

Loading editor…

Example 5 - Convert to Uppercase

Loading editor…

Example 6 - Length of Each String

Loading editor…

Advantages of List Comprehension

  • Simple and easy to read.
  • Requires fewer lines of code.
  • Creates lists quickly.
  • Can include conditions.
  • Improves code readability.

Difference Between Normal Loop and List Comprehension

Normal Loop List Comprehension
Requires multiple lines. Usually written in one line.
Uses append() repeatedly. Creates the list directly.
More code. Less code.
Easy for complex logic. Best for simple list creation.
📝 Key Takeaways
  • A list is an ordered, mutable collection that allows duplicate values
  • append(), insert(), extend(), remove(), pop() and clear() modify lists
  • Lists support slicing, sorting, membership tests and list operators
  • sort() and sorted() order lists in ascending or descending order
  • Nested lists and list comprehensions build structured data in one expression

🧠 Test Your Knowledge

70 Questions
Progress: 0 / 70

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.