Nearby lessons

59 of 108

Python - List Data Structure

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Creating List Objects

There are different ways to create a list in Python.

Method 1 - Create an Empty List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[]

Method 2 - Create a List with Known Elements

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 40]

Method 3 - Using list() Function

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[0, 2, 4, 6, 8]

Method 4 - Using split() Method

The split() method returns a list.

Example - split()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
['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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
10
30

Example - Negative Index

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
40
30

Accessing Elements Using Slice Operator

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

Example 1 - Slice Operator

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[20, 30, 40]

Example 2 - Complete List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 40, 50]

Quick Summary

Topic Description
ListOrdered collection of objects
Insertion OrderPreserved
Duplicate ObjectsAllowed
Heterogeneous ObjectsAllowed
DynamicSize can be increased or decreased
MutableElements can be modified
RepresentationSquare brackets []
Positive IndexLeft to Right
Negative IndexRight to Left
Slice OperatorAccess multiple elements

Important Notes

  • A list represents a group of individual objects as a single entity.
  • Lists preserve insertion order.
  • Duplicate elements are allowed.
  • Different data types can be stored in the same list.
  • Lists are dynamic in nature.
  • Lists are mutable, so their contents can be modified.
  • Python supports both positive and negative indexing.
  • List elements can be accessed using indexes or the slice operator.
  • An empty list can be created using [].
  • The list() function and split() method can also be used to create list objects.

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
10
20
30

Example 3 - Print Only Odd Numbers

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
15
25
35

Example 4 - Print Squares of List Elements

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 300, 40]

Example 2 - Update First Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[100, 20, 30]

Example 3 - Update Last Element Using Negative Index

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 400]

Example 4 - Update Multiple Elements Using Slice

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 200, 300, 400, 50]

Important Notes

  • Lists are mutable, so their contents can be changed.
  • Elements can be updated using positive or negative indexes.
  • Multiple elements can be updated using the slice operator.
  • The for loop is the simplest way to traverse a list.
  • The while loop is useful when index values are required.
  • len() returns the total number of elements in the list.

Quick Summary

Topic Description
Traversing Accessing every element one by one.
for Loop Traverses elements directly.
while Loop Traverses elements using indexes.
Positive Index Starts from 0.
Negative Index Starts from -1.
Mutable Elements can be modified after creation.
Update Element Use index or slice operator.
len() Returns the number of elements.

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Add One Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 40]

Example 2 - Append Different Data Types

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
How Many Elements : 4

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

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

Important Points - append()

  • Adds only one element at a time.
  • Always inserts the element at the end of the list.
  • The original list is modified.

insert() Method

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

Syntax:

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Insert an Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 40]

Example 3 - Insert at Last

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 40]

Example 5 - Negative Index

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Extend Using Another List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 40, 50, 60]

Example 2 - Extend Using Tuple

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 40, 50]

Example 3 - Extend Using String

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, [30, 40]]

[10, 20, 30, 40]

Quick Summary

Method Purpose
append() Adds one element at the end.
insert() Inserts an element at a specified index.
extend() Adds all elements of another iterable.

Important Notes

  • append() always adds one element at the end.
  • insert() inserts an element at the specified index.
  • extend() adds multiple elements from another iterable.
  • append() accepts any object.
  • extend() accepts only iterable objects.
  • All three methods modify the original list.
  • Strings, tuples, lists, and sets can be passed to extend().

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Remove an Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 30, 40]

Example 2 - Remove Duplicate Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
ValueError: list.remove(x): x not in list

Important Notes - remove()

  • Removes an element by value.
  • Only the first matching element is removed.
  • If the element is not available, Python raises ValueError.

pop() Method

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

It also returns the removed element.

Syntax:

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Remove Last Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
Removed Element : 40

[10, 20, 30]

Explanation

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

Example 2 - Remove Element at Index

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
Removed Element : 20

[10, 30, 40]

Example 3 - Invalid Index

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
IndexError: pop index out of range

Important Notes - pop()

  • Removes an element using its index.
  • Returns the removed element.
  • If no index is given, the last element is removed.
  • If the index is invalid, Python raises IndexError.

clear() Method

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

After using clear(), the list becomes empty.

Syntax:

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Remove All Elements

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[]

Explanation

The list object still exists.

Only its elements are removed.

Example 2 - Check List After clear()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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.

Quick Comparison

Feature remove() pop() clear()
Removes by Value Index All Elements
Returns Removed Element No Yes No
Raises Error ValueError IndexError No
List Exists After Operation Yes Yes Yes

Real World Usage

These methods are commonly used in:

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

Important Notes

  • remove() removes an element by value.
  • remove() deletes only the first matching element.
  • pop() removes an element by index.
  • pop() returns the removed element.
  • If no index is given, pop() removes the last element.
  • clear() removes all elements from the list.
  • After clear(), the list still exists but becomes empty.

Quick Summary

Method Purpose
remove(value) Removes the specified element.
pop(index) Removes and returns an element.
pop() Removes the last element.
clear() Removes all elements.

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Delete an Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 30, 40]

Example 2 - Delete Multiple Elements

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 50, 60]

Example 3 - Delete Entire List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
NameError: name '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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30]

Example 2 - Pop Operation

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
Removed : 30

[10, 20]

Example 3 - Complete Stack Program

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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.

Comparison of Removing Methods

Method Removes By Returns Value
remove() Element Value No
pop() Index Yes
clear() All Elements No
del Index, Slice or Entire List No

Important Notes

  • del is a Python keyword.
  • del can delete a single element, multiple elements, or the complete list.
  • clear() removes all elements but keeps the list object.
  • A stack follows the LIFO (Last In, First Out) principle.
  • append() is used for Push operation.
  • pop() is used for Pop operation.
  • The last inserted element is removed first in a stack.

Complete List Methods Summary

Method Description
append()Add one element.
extend()Add multiple elements.
insert()Insert at specified index.
remove()Remove by value.
pop()Remove by index and return element.
clear()Remove all elements.
delDelete elements or entire list.

Quick Revision

Topic Remember
append() Add one element.
extend() Add multiple elements.
insert() Insert at index.
remove() Remove by value.
pop() Remove by index.
clear() Empty the list.
del Delete list or elements.
Stack LIFO Data Structure.

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Find Length of a List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
5

Example 2 - Length of an Empty List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
0

Example 3 - Length of a Heterogeneous List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Count Duplicate Elements

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
3

Example 2 - Count String Elements

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
3

Example 3 - Element Not Present

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Find Index

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
2

Example 2 - Duplicate Elements

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
0

Explanation

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

Example 3 - Element Not Available

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
ValueError: 100 is not in list

Example 4 - Search from a Specific Index

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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.

Comparison of List Information Functions

Function / Method Purpose
len() Returns the number of elements.
count() Returns the number of occurrences of an element.
index() Returns the index of the first occurrence.

Real World Usage

These functions are commonly used in:

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

Important Notes

  • len() returns the total number of elements.
  • count() returns how many times an element appears.
  • index() returns the index of the first occurrence only.
  • count() returns 0 if the element is not found.
  • index() raises ValueError if the element is not found.
  • index() supports optional start and end positions.

Quick Summary

Function / Method Description
len() Returns the total number of elements.
count() Counts the occurrences of an element.
index() Returns the index of the first occurrence.

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Reverse a List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
['C++', 'C', 'Java', 'Python']

Important Notes - reverse()

  • The original list is modified.
  • No new list is created.
  • The order of elements becomes exactly opposite.

sort() Method

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

It modifies the original list.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Sort Numbers

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 40, 50]

Example 2 - Sort Strings

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
['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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Descending Order

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[50, 40, 30, 20, 10]

Example 2 - Descending String Order

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
['Python', 'Java', 'HTML', 'C']

Important Notes - sort()

  • The original list is modified.
  • Ascending order is the default order.
  • Use reverse=True for descending order.
  • All elements should be of compatible data types.

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Using sorted()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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.

Comparison Table

Feature reverse() sort() sorted()
Creates New List No No Yes
Modifies Original List Yes Yes No
Ascending Order No Yes Yes
Descending Order No Yes (reverse=True) Yes (reverse=True)

Real World Usage

Ordering methods are commonly used in:

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

Important Notes

  • reverse() changes only the current order.
  • sort() arranges elements in ascending order by default.
  • Use reverse=True for descending order.
  • sorted() returns a new sorted list.
  • The original list remains unchanged when using sorted().
  • Lists containing incompatible data types cannot be sorted.

Quick Summary

Method / Function Purpose
reverse() Reverse the current order.
sort() Sort the original list.
sorted() Create a new sorted list.

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Join Two Lists

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 30, 40, 50, 60]

Example 2 - Join String Lists

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
['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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Repeat a List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[10, 20, 10, 20, 10, 20]

Example 2 - Repeat String List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
['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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
True

Example 2 - Not Equal Operator

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
True

Example 3 - Greater Than Operator

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
True

False

Example 2 - not in Operator

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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.

Comparison of List Operators

Operator Purpose
+ Join two lists.
* Repeat list elements.
== Check equality.
!= Check inequality.
<, >, <=, >= Compare list elements.
in Check whether an element exists.
not in Check whether an element does not exist.

Important Notes

  • The + operator joins two lists.
  • The * operator repeats list elements.
  • Comparison operators compare elements from left to right.
  • The in operator checks whether an element exists.
  • The not in operator checks whether an element does not exist.
  • The + and * operators create new lists.

Quick Summary

Operator Description
+Concatenates two lists.
*Repeats list elements.
==Checks equality.
!=Checks inequality.
<, >Compares list elements.
inChecks element existence.
not inChecks element absence.

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[[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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Example 5 - Matrix Elements

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Create a List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[1, 2, 3, 4, 5]

Example 2 - Squares Using List Comprehension

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[1, 4, 9, 16, 25]

Example 3 - Even Numbers

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Example 4 - Odd Numbers

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Example 5 - Convert to Uppercase

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
['PYTHON', 'JAVA', 'C']

Example 6 - Length of Each String

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
[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.

Important Notes

  • A nested list contains one or more lists as its elements.
  • Nested lists are useful for representing matrices and tables.
  • Nested loops are commonly used to traverse nested lists.
  • List comprehension provides a short way to create lists.
  • Conditions can also be used inside list comprehension.
  • List comprehension improves code readability and reduces code size.

Quick Summary

Topic Description
Nested List A list containing one or more lists.
Matrix Represented using a nested list.
Nested Loop Used to traverse nested lists.
List Comprehension Short syntax to create lists.
Condition Can be used inside list comprehension.

🧠 Test Your Knowledge

72 Questions

Progress: 0 / 72
Keep Going!Python - Tuple Collection