DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 23: List Methods, List Operators & List Comprehension

1. What is a List?

A list is a collection of elements stored in a single variable.

In Python, a list:

  • Is ordered.
  • Is mutable (we can modify it).
  • Allows duplicate values.
  • Can store different data types. Example:
l = [10, 20, 30, 40]

print(l)
print(l[0])
print(l[1])
print(l[2])
Enter fullscreen mode Exit fullscreen mode
Output:
[10, 20, 30, 40]
10
20
30
Enter fullscreen mode Exit fullscreen mode

We can access list elements using their index. Indexing starts from 0.

2. What is an Iterable?

An iterable is an object that allows us to access its elements one by one.

For example, we can access individual characters in a string using indexing.

name = 'ajay'

print(name[0])
print(name[1])
print(name[2])
print(name[3])
Enter fullscreen mode Exit fullscreen mode
Output:
a
j
a
y
Enter fullscreen mode Exit fullscreen mode

Similarly, we can access elements in a list:

l = [10, 20, 30]

print(l[0])
print(l[1])
print(l[2])
Enter fullscreen mode Exit fullscreen mode

Common iterable data types:

  • List
  • String
  • Tuple
  • Dictionary
  • Set

Common non-iterable data types:

  • Integer (int)
  • Float (float)
  • Boolean (bool)

Example:

no = 123

for num in no:
    print(num)
Enter fullscreen mode Exit fullscreen mode

This gives a TypeError because an integer is not iterable.

Remember: A dictionary is iterable, and iterating over it directly gives its keys. A set is also iterable, but it does not maintain a guaranteed element order.

3. Difference Between append() and extend()

Both append() and extend() are list methods used to add elements to a list. However, they work differently.

append()

The append() method adds a single item to the end of a list.

l1 = [10, 20, 30]
l2 = [40, 50, 60]

print(len(l1))

l1.append(l2)

print(l1)
print(len(l1))
Enter fullscreen mode Exit fullscreen mode
Output:
3
[10, 20, 30, [40, 50, 60]]
4
Enter fullscreen mode Exit fullscreen mode

Here, the entire l2 list is added as one element inside l1.

Therefore, the length becomes 4.

extend()

The extend() method adds each element from another iterable to the existing list.

l1 = [10, 20, 30]
l2 = [40, 50, 60]

print(len(l1))

l1.extend(l2)

print(l1)
print(len(l1))
Enter fullscreen mode Exit fullscreen mode
Output:
3
[10, 20, 30, 40, 50, 60]
6
Enter fullscreen mode Exit fullscreen mode

Here, the elements of l2 are added individually to l1.

Therefore, the length becomes 6.

Feature append() extend()
Purpose Adds one item Adds elements from an iterable
Argument One object An iterable
List behavior Adds the entire list as one element Adds each element individually
Length Increases by 1 Increases by the number of added elements
Example l1.append(l2) l1.extend(l2)

4. reverse() Method

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

l1 = [10, 20, 30]

l1.reverse()

print(l1)
Enter fullscreen mode Exit fullscreen mode
Output:
[30, 20, 10]
Enter fullscreen mode Exit fullscreen mode

Note: reverse() modifies the original list. It does not return a new reversed list.

5. sort() Method

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

l1 = [10, 6, 3, 2, 7]

l1.sort()

print(l1)
Enter fullscreen mode Exit fullscreen mode
Output:
[2, 3, 6, 7, 10]
Enter fullscreen mode Exit fullscreen mode

Sorting in descending order

We can use reverse=True to arrange elements in descending order.

l1 = [10, 6, 3, 2, 7]

l1.sort(reverse=True)

print(l1)
Enter fullscreen mode Exit fullscreen mode
Output:
[10, 7, 6, 3, 2]
Enter fullscreen mode Exit fullscreen mode

Sorting strings

We can also sort strings alphabetically.

l1 = ['ajay', 'vijay', 'surya', 'sk']

l1.sort()

print(l1)
Enter fullscreen mode Exit fullscreen mode
Output:
['ajay', 'sk', 'surya', 'vijay']
Enter fullscreen mode Exit fullscreen mode

6. TypeError While Sorting Different Data Types

What happens if we try to sort a list containing both integers and strings?

l1 = [10, 'ajay', 'vijay', 'surya', 2, 7]

l1.sort()

print(l1)
Enter fullscreen mode Exit fullscreen mode
Output:

TypeError: '<' not supported between instances of 'str' and 'int'
Enter fullscreen mode Exit fullscreen mode

Why does this error occur?

Python needs to compare elements to decide their sorting order.

For example:

10 < 2

Output:

False

But what happens when we compare an integer with a string?

10 < 'ajith'

This produces a TypeError because Python does not support the less-than comparison between an integer and a string.

Python uses comparison methods such as lt() to perform less-than comparisons.

7. Operator Overloading

Operator overloading means using the same operator to perform different operations depending on the objects involved.

For example:

print(10 + 20)
print('Hello' + ' Python')
print([10, 20] + [30, 40])
Enter fullscreen mode Exit fullscreen mode
Output:

30
Hello Python
[10, 20, 30, 40]
Enter fullscreen mode Exit fullscreen mode

The + operator performs addition for numbers and concatenation for strings and lists.

Python uses special methods to implement these operations.

Operator Special Method
+ __add__()
< __lt__()
> __gt__()
== __eq__()
!= __ne__()

8. List and Set: Duplicate Values

A list allows duplicate values, whereas a set stores only unique values.

List example:

l = [10, 20, 10, 20]

print(l)
Enter fullscreen mode Exit fullscreen mode
Output:

[10, 20, 10, 20]
Enter fullscreen mode Exit fullscreen mode

Set example:

s = set()

s.add(10)
s.add(20)
s.add(10)
s.add(20)

print(s)
Enter fullscreen mode Exit fullscreen mode
Output:

{10, 20}
Enter fullscreen mode Exit fullscreen mode

The duplicate values are not stored in a set.

9. List Operators

Python supports different operators on lists.

1. Concatenation (+)

The + operator joins two lists and creates a new list.

l1 = [10, 20, 30]
l2 = [40, 50, 60]

print(l1 + l2)
Enter fullscreen mode Exit fullscreen mode
Output:

[10, 20, 30, 40, 50, 60]
Enter fullscreen mode Exit fullscreen mode

2. Repetition (*)

The * operator repeats the elements of a list.

l1 = [10, 20, 30]

print(l1 * 2)
Enter fullscreen mode Exit fullscreen mode
Output:

[10, 20, 30, 10, 20, 30]
Enter fullscreen mode Exit fullscreen mode

3. Equality (==)

The == operator checks whether two lists have the same elements in the same order.

l1 = [10, 20, 30]
l2 = [10, 20, 30]

print(l1 == l2)
Enter fullscreen mode Exit fullscreen mode

Output:

True
Enter fullscreen mode Exit fullscreen mode

Example with different order:

l1 = [10, 20, 30]
l2 = [20, 10, 30]

print(l1 == l2)
Enter fullscreen mode Exit fullscreen mode
Output:

False
Enter fullscreen mode Exit fullscreen mode

Order matters when comparing lists.

4. Not Equal (!=)

The != operator checks whether two lists are different.


l1 = [10, 20, 30]
l2 = [10, 20, 40]

print(l1 != l2)
Enter fullscreen mode Exit fullscreen mode
Output:

True
Enter fullscreen mode Exit fullscreen mode

5. Greater Than (>) and Less Than (<)

Python compares lists element by element from left to right.

l1 = [10, 20, 30]
l2 = [10, 20, 40]

print(l1 > l2)
print(l1 < l2)
Enter fullscreen mode Exit fullscreen mode
Output:

False
True
Enter fullscreen mode Exit fullscreen mode

The first two elements are equal. Python compares the third elements: 30 and 40.

Since 30 is smaller than 40, l1 < l2 returns True.

Comparing strings inside lists

l1 = ['abcd', 'EFGH']
l2 = ['ABCD', 'EFGH']

print(l1 == l2)
Enter fullscreen mode Exit fullscreen mode
Output:

False
Enter fullscreen mode Exit fullscreen mode

String comparisons are case-sensitive. Therefore, 'abcd' and 'ABCD' are different.

11. List Comprehension

List comprehension is a shorter way to create a new list from an iterable.

Instead of writing multiple lines using a for loop and append(), we can write everything in a single line.

Syntax:

[expression for item in iterable]

Example 1: Creating a list of numbers

Using a normal for loop:


l1 = []

for num in range(1, 11):
    l1.append(num)

print(l1)
Enter fullscreen mode Exit fullscreen mode

Using list comprehension:

l1 = [num for num in range(1, 11)]

print(l1)

Enter fullscreen mode Exit fullscreen mode
Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

Example 2: Creating a list of squares

Using a normal for loop:

l2 = []

for num in range(1, 6):
    l2.append(num * num)

print(l2)
Enter fullscreen mode Exit fullscreen mode

Using list comprehension:

l2 = [num * num for num in range(1, 6)]

print(l2)
Enter fullscreen mode Exit fullscreen mode
Output:

[1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

Example 3: Finding even numbers

We can use an if condition inside list comprehension.

Using a normal for loop:

l3 = []

for num in range(1, 11):
    if num % 2 == 0:
        l3.append(num)

print(l3)
Enter fullscreen mode Exit fullscreen mode

Using list comprehension:

l3 = [num for num in range(1, 11) if num % 2 == 0]

print(l3)
Enter fullscreen mode Exit fullscreen mode
Output:

[2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Example 4: Using if-else in List Comprehension

We can also use an if-else condition to generate different values.

l = [10, 20, 30, 40, 50]

result = [
    "Multiple of 20" if num % 20 == 0 else "Not Multiple of 20"
    for num in l
]

print(result)
Enter fullscreen mode Exit fullscreen mode
Output:

['Not Multiple of 20', 'Multiple of 20', 'Not Multiple of 20', 'Multiple of 20', 'Not Multiple of 20']
Enter fullscreen mode Exit fullscreen mode

The same logic using a normal for loop:

l = [10, 20, 30, 40, 50]
result = []

for num in l:
    if num % 20 == 0:
        result.append("Multiple of 20")
    else:
        result.append("Not Multiple of 20")

print(result)

Enter fullscreen mode Exit fullscreen mode

Both approaches produce the same output.

Top comments (0)