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

🐍Code Cell
1list = [10, "A", "B", 20, 30, 10]
2 
3print(list)
Output
[10, 'A', 'B', 20, 30, 10]

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

🐍Code Cell
1list = [10, 20, 30]
Output
No output captured.

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
🐍Code Cell
1list = [10, "A", "B", 20, 30, 10]
Output
No output captured.

Creating List Objects

There are different ways to create a list in Python.

Method 1 - Create an Empty List

🐍Code Cell
1list = []
2 
3print(list)
4print(type(list))
Output
[]

Method 2 - Create a List with Known Elements

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3print(list)
Output
[10, 20, 30, 40]

Method 3 - Using list() Function

🐍Code Cell
1list = list(range(0, 10, 2))
2 
3print(list)
Output
[0, 2, 4, 6, 8]

Method 4 - Using split() Method

The split() method returns a list.

Example - split()

🐍Code Cell
1s = "Learning Python is very Easy"
2 
3list = s.split()
4 
5print(list)
Output
['Learning', 'Python', 'is', 'very', 'Easy']

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

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3print(list[0])
4print(list[2])
Output
10
30

Example - Negative Index

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3print(list[-1])
4print(list[-2])
Output
40
30

Accessing Elements Using Slice Operator

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

Example 1 - Slice Operator

🐍Code Cell
1list = [10, 20, 30, 40, 50]
2 
3print(list[1:4])
Output
[20, 30, 40]

Example 2 - Complete List

🐍Code Cell
1list = [10, 20, 30, 40, 50]
2 
3print(list[:])
Output
[10, 20, 30, 40, 50]

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

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3for x in list:
4 print(x)
Output
10
20
30
40

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

🐍Code Cell
1list = [10, 15, 20, 25, 30, 35]
2 
3for x in list:
4 if x % 2 == 0:
5 print(x)
Output
10
20
30

Example 3 - Print Only Odd Numbers

🐍Code Cell
1list = [10, 15, 20, 25, 30, 35]
2 
3for x in list:
4 if x % 2 != 0:
5 print(x)
Output
15
25
35

Example 4 - Print Squares of List Elements

🐍Code Cell
1list = [1, 2, 3, 4, 5]
2 
3for x in list:
4 print(x * x)
Output
1
4
9
16
25

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

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3i = 0
4 
5while i < len(list):
6 print(list[i])
7 i = i + 1
Output
10
20
30
40

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

🐍Code Cell
1list = [10, 20, 30, 40, 50]
2 
3i = len(list) - 1
4 
5while i >= 0:
6 print(list[i])
7 i = i - 1
Output
50
40
30
20
10

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

🐍Code Cell
1list = ["A", "B", "C", "D"]
2 
3n = len(list)
4 
5for i in range(n):
6 print(
7 list[i],
8 "Positive Index :", i,
9 "Negative Index :", i - n
10 )
Output
A Positive Index : 0 Negative Index : -4
B Positive Index : 1 Negative Index : -3
C Positive Index : 2 Negative Index : -2
D Positive Index : 3 Negative Index : -1

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

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3list[2] = 300
4 
5print(list)
Output
[10, 20, 300, 40]

Example 2 - Update First Element

🐍Code Cell
1list = [10, 20, 30]
2 
3list[0] = 100
4 
5print(list)
Output
[100, 20, 30]

Example 3 - Update Last Element Using Negative Index

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3list[-1] = 400
4 
5print(list)
Output
[10, 20, 30, 400]

Example 4 - Update Multiple Elements Using Slice

🐍Code Cell
1list = [10, 20, 30, 40, 50]
2 
3list[1:4] = [200, 300, 400]
4 
5print(list)
Output
[10, 200, 300, 400, 50]

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

🐍Code Cell
1list.append(element)
Output
No output captured.

Example 1 - Add One Element

🐍Code Cell
1list = [10, 20, 30]
2 
3list.append(40)
4 
5print(list)
Output
[10, 20, 30, 40]

Example 2 - Append Different Data Types

🐍Code Cell
1list = []
2 
3list.append(10)
4list.append("Python")
5list.append(10.5)
6list.append(True)
7 
8print(list)
Output
[10, 'Python', 10.5, True]

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

🐍Code Cell
1list = []
2 
3n = int(input("How Many Elements : "))
4 
5for i in range(n):
6 element = input("Enter Element : ")
7 list.append(element)
8 
9print(list)
Output
How Many Elements : 4

Enter Element : A
Enter Element : B
Enter Element : C
Enter Element : D

['A', 'B', 'C', 'D']

insert() Method

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

Syntax:

Syntax

🐍Code Cell
1list.insert(index, element)
Output
No output captured.

Example 1 - Insert an Element

🐍Code Cell
1list = [10, 20, 30]
2 
3list.insert(1, 100)
4 
5print(list)
Output
[10, 100, 20, 30]

Explanation

The element is inserted at the specified index.

Existing elements are automatically shifted to the right.

Example 2 - Insert at Beginning

🐍Code Cell
1list = [20, 30, 40]
2 
3list.insert(0, 10)
4 
5print(list)
Output
[10, 20, 30, 40]

Example 3 - Insert at Last

🐍Code Cell
1list = [10, 20, 30]
2 
3list.insert(len(list), 40)
4 
5print(list)
Output
[10, 20, 30, 40]

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

🐍Code Cell
1list = [10, 20, 30]
2 
3list.insert(100, 40)
4 
5print(list)
Output
[10, 20, 30, 40]

Example 5 - Negative Index

🐍Code Cell
1list = [10, 20, 30]
2 
3list.insert(-1, 200)
4 
5print(list)
Output
[10, 20, 200, 30]

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

🐍Code Cell
1list.extend(iterable)
Output
No output captured.

Example 1 - Extend Using Another List

🐍Code Cell
1list1 = [10, 20, 30]
2 
3list2 = [40, 50, 60]
4 
5list1.extend(list2)
6 
7print(list1)
Output
[10, 20, 30, 40, 50, 60]

Example 2 - Extend Using Tuple

🐍Code Cell
1list = [10, 20]
2 
3tuple1 = (30, 40, 50)
4 
5list.extend(tuple1)
6 
7print(list)
Output
[10, 20, 30, 40, 50]

Example 3 - Extend Using String

🐍Code Cell
1list = [10, 20]
2 
3list.extend("ABC")
4 
5print(list)
Output
[10, 20, 'A', 'B', 'C']

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()

🐍Code Cell
1list1 = [10, 20]
2 
3list1.append([30, 40])
4 
5print(list1)
6 
7list2 = [10, 20]
8 
9list2.extend([30, 40])
10 
11print(list2)
Output
[10, 20, [30, 40]]
[10, 20, 30, 40]

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

🐍Code Cell
1list.remove(element)
Output
No output captured.

Example 1 - Remove an Element

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3list.remove(20)
4 
5print(list)
Output
[10, 30, 40]

Example 2 - Remove Duplicate Element

🐍Code Cell
1list = [10, 20, 30, 20, 40]
2 
3list.remove(20)
4 
5print(list)
Output
[10, 30, 20, 40]

Explanation

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

Other duplicate elements remain in the list.

Example 3 - Element Not Present

🐍Code Cell
1list = [10, 20, 30]
2 
3list.remove(100)
Output
ValueError: list.remove(x): x not in list

pop() Method

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

It also returns the removed element.

Syntax:

Syntax

🐍Code Cell
1list.pop(index)
Output
No output captured.

Example 1 - Remove Last Element

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3x = list.pop()
4 
5print("Removed Element :", x)
6print(list)
Output
Removed Element : 40
[10, 20, 30]

Explanation

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

Example 2 - Remove Element at Index

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3x = list.pop(1)
4 
5print("Removed Element :", x)
6print(list)
Output
Removed Element : 20
[10, 30, 40]

Example 3 - Invalid Index

🐍Code Cell
1list = [10, 20, 30]
2 
3list.pop(10)
Output
IndexError: pop index out of range

clear() Method

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

After using clear(), the list becomes empty.

Syntax:

Syntax

🐍Code Cell
1list.clear()
Output
No output captured.

Example 1 - Remove All Elements

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3list.clear()
4 
5print(list)
Output
[]

Explanation

The list object still exists.

Only its elements are removed.

Example 2 - Check List After clear()

🐍Code Cell
1list = ["Python", "Java", "C"]
2 
3list.clear()
4 
5print("Length :", len(list))
6print(list)
Output
Length : 0
[]

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

🐍Code Cell
1del list[index]
2 
3del list[start:end]
4 
5del list
Output
No output captured.

Example 1 - Delete an Element

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3del list[1]
4 
5print(list)
Output
[10, 30, 40]

Example 2 - Delete Multiple Elements

🐍Code Cell
1list = [10, 20, 30, 40, 50, 60]
2 
3del list[1:4]
4 
5print(list)
Output
[10, 50, 60]

Example 3 - Delete Entire List

🐍Code Cell
1my_list = [10, 20, 30]
2 
3del my_list
4 
5print(my_list)
Output
NameError: name 'my_list' is not defined

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

🐍Code Cell
1stack = []
2 
3stack.append(10)
4stack.append(20)
5stack.append(30)
6 
7print(stack)
Output
[10, 20, 30]

Example 2 - Pop Operation

🐍Code Cell
1stack = [10, 20, 30]
2 
3print("Removed :", stack.pop())
4 
5print(stack)
Output
Removed : 30
[10, 20]

Example 3 - Complete Stack Program

🐍Code Cell
1stack = []
2 
3stack.append(100)
4stack.append(200)
5stack.append(300)
6 
7print("Stack :", stack)
8 
9print("Removed :", stack.pop())
10 
11print("Stack :", stack)
12 
13stack.append(400)
14 
15print("Stack :", stack)
Output
Stack : [100, 200, 300]
Removed : 300
Stack : [100, 200]
Stack : [100, 200, 400]

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

🐍Code Cell
1len(list)
Output
No output captured.

Example 1 - Find Length of a List

🐍Code Cell
1list = [10, 20, 30, 40, 50]
2 
3print(len(list))
Output
5

Example 2 - Length of an Empty List

🐍Code Cell
1list = []
2 
3print(len(list))
Output
0

Example 3 - Length of a Heterogeneous List

🐍Code Cell
1list = [10, "Python", 20.5, True]
2 
3print(len(list))
Output
4

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

🐍Code Cell
1list.count(element)
Output
No output captured.

Example 1 - Count Duplicate Elements

🐍Code Cell
1list = [10, 20, 10, 30, 10, 40]
2 
3print(list.count(10))
Output
3

Example 2 - Count String Elements

🐍Code Cell
1list = ["A", "B", "A", "C", "A"]
2 
3print(list.count("A"))
Output
3

Example 3 - Element Not Present

🐍Code Cell
1list = [10, 20, 30]
2 
3print(list.count(100))
Output
0

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

🐍Code Cell
1list.index(element)
Output
No output captured.

Example 1 - Find Index

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3print(list.index(30))
Output
2

Example 2 - Duplicate Elements

🐍Code Cell
1list = [10, 20, 10, 30, 10]
2 
3print(list.index(10))
Output
0

Explanation

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

Example 3 - Element Not Available

🐍Code Cell
1list = [10, 20, 30]
2 
3print(list.index(100))
Output
ValueError: 100 is not in list

Example 4 - Search from a Specific Index

🐍Code Cell
1list = [10, 20, 10, 30, 10]
2 
3print(list.index(10, 1))
Output
2

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

🐍Code Cell
1list = [10, 20, 10, 30, 10, 40]
2 
3print(list.index(10, 2, 5))
Output
2

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

🐍Code Cell
1list.reverse()
Output
No output captured.

Example 1 - Reverse a List

🐍Code Cell
1numbers = [10, 20, 30, 40, 50]
2 
3numbers.reverse()
4 
5print(numbers)
Output
[50, 40, 30, 20, 10]

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

🐍Code Cell
1languages = ["Python", "Java", "C", "C++"]
2 
3languages.reverse()
4 
5print(languages)
Output
['C++', 'C', 'Java', 'Python']

sort() Method

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

It modifies the original list.

Syntax

🐍Code Cell
1list.sort()
Output
No output captured.

Example 1 - Sort Numbers

🐍Code Cell
1numbers = [40, 10, 30, 20, 50]
2 
3numbers.sort()
4 
5print(numbers)
Output
[10, 20, 30, 40, 50]

Example 2 - Sort Strings

🐍Code Cell
1languages = ["Java", "Python", "C", "HTML"]
2 
3languages.sort()
4 
5print(languages)
Output
['C', 'HTML', 'Java', 'Python']

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

🐍Code Cell
1list.sort(reverse=True)
Output
No output captured.

Example 1 - Descending Order

🐍Code Cell
1numbers = [40, 10, 30, 20, 50]
2 
3numbers.sort(reverse=True)
4 
5print(numbers)
Output
[50, 40, 30, 20, 10]

Example 2 - Descending String Order

🐍Code Cell
1languages = ["Java", "Python", "C", "HTML"]
2 
3languages.sort(reverse=True)
4 
5print(languages)
Output
['Python', 'Java', 'HTML', 'C']

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

🐍Code Cell
1list = [10, "Python", 20]
2 
3list.sort()
Output
TypeError: '<' not supported between instances of 'str' and 'int'

sorted() Function

The sorted() function returns a new sorted list.

The original list remains unchanged.

Syntax

🐍Code Cell
1sorted(iterable)
2 
3sorted(iterable, reverse=True)
Output
No output captured.

Example 1 - Using sorted()

🐍Code Cell
1numbers = [40, 10, 30, 20]
2 
3new_list = sorted(numbers)
4 
5print(new_list)
6 
7print(numbers)
Output
[10, 20, 30, 40]
[40, 10, 30, 20]

Explanation

The sorted() function returns a new sorted list.

The original list is not modified.

Example 2 - Descending Order

🐍Code Cell
1numbers = [40, 10, 30, 20]
2 
3new_list = sorted(numbers, reverse=True)
4 
5print(new_list)
Output
[40, 30, 20, 10]

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

🐍Code Cell
1list3 = list1 + list2
Output
No output captured.

Example 1 - Join Two Lists

🐍Code Cell
1list1 = [10, 20, 30]
2 
3list2 = [40, 50, 60]
4 
5list3 = list1 + list2
6 
7print(list3)
Output
[10, 20, 30, 40, 50, 60]

Example 2 - Join String Lists

🐍Code Cell
1list1 = ["Python", "Java"]
2 
3list2 = ["C", "C++"]
4 
5print(list1 + list2)
Output
['Python', 'Java', 'C', 'C++']

Important Notes - (+)

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

Example 3 - Invalid Concatenation

🐍Code Cell
1list = [10, 20, 30]
2 
3print(list + 40)
Output
TypeError: can only concatenate list (not "int") to list

Repetition Operator (*)

The * operator repeats the elements of a list.

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

Syntax

🐍Code Cell
1new_list = list * number
Output
No output captured.

Example 1 - Repeat a List

🐍Code Cell
1list = [10, 20]
2 
3print(list * 3)
Output
[10, 20, 10, 20, 10, 20]

Example 2 - Repeat String List

🐍Code Cell
1languages = ["Python", "Java"]
2 
3print(languages * 2)
Output
['Python', 'Java', 'Python', 'Java']

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

🐍Code Cell
1list1 = [10, 20, 30]
2 
3list2 = [10, 20, 30]
4 
5print(list1 == list2)
Output
True

Example 2 - Not Equal Operator

🐍Code Cell
1list1 = [10, 20]
2 
3list2 = [10, 30]
4 
5print(list1 != list2)
Output
True

Example 3 - Greater Than Operator

🐍Code Cell
1list1 = [30, 40]
2 
3list2 = [10, 20]
4 
5print(list1 > list2)
Output
True

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

🐍Code Cell
1list = [10, 20, 30, 40]
2 
3print(20 in list)
4 
5print(100 in list)
Output
True
False

Example 2 - not in Operator

🐍Code Cell
1list = [10, 20, 30]
2 
3print(50 not in list)
4 
5print(20 not in list)
Output
True
False

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

🐍Code Cell
1list = [
2 [10, 20, 30],
3 [40, 50, 60],
4 [70, 80, 90]
5]
6 
7print(list)
Output
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]

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

🐍Code Cell
1list = [
2 [10, 20, 30],
3 [40, 50, 60],
4 [70, 80, 90]
5]
6 
7print(list[0][0])
8print(list[1][2])
9print(list[2][1])
Output
10
60
80

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

🐍Code Cell
1list = [
2 [10, 20, 30],
3 [40, 50, 60],
4 [70, 80, 90]
5]
6 
7for row in list:
8 for value in row:
9 print(value, end=" ")
10 print()
Output
10 20 30 
40 50 60 
70 80 90

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

🐍Code Cell
1matrix = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5]
6 
7for row in matrix:
8 print(row)
Output
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Example 5 - Matrix Elements

🐍Code Cell
1matrix = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5]
6 
7for row in matrix:
8 for value in row:
9 print(value, end=" ")
10 print()
Output
1 2 3 
4 5 6 
7 8 9

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

🐍Code Cell
1[expression for variable in iterable]
Output
No output captured.

Example 1 - Create a List

🐍Code Cell
1list = [x for x in range(1, 6)]
2 
3print(list)
Output
[1, 2, 3, 4, 5]

Example 2 - Squares Using List Comprehension

🐍Code Cell
1list = [x*x for x in range(1, 6)]
2 
3print(list)
Output
[1, 4, 9, 16, 25]

Example 3 - Even Numbers

🐍Code Cell
1list = [x for x in range(1, 21) if x % 2 == 0]
2 
3print(list)
Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Example 4 - Odd Numbers

🐍Code Cell
1list = [x for x in range(1, 21) if x % 2 != 0]
2 
3print(list)
Output
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Example 5 - Convert to Uppercase

🐍Code Cell
1names = ["python", "java", "c"]
2 
3upper = [name.upper() for name in names]
4 
5print(upper)
Output
['PYTHON', 'JAVA', 'C']

Example 6 - Length of Each String

🐍Code Cell
1names = ["Python", "Java", "HTML"]
2 
3lengths = [len(name) for name in names]
4 
5print(lengths)
Output
[6, 4, 4]

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