Chapter 7: Lists in Python

Introduction to Lists

What is a List?

List is a collection of values or an ordered sequence of values/items. The items in a list can be of any type such as string, integer, float or even a list.

  • Elements are enclosed in Square brackets [ ]
  • Items are separated by commas
  • Lists are mutable (values can be modified)
  • Lists are heterogeneous (different data types allowed)

L1 = [1, 2, 5, 4]

L1 = [1, 2.25, "python", "10+j12", [10, 20, 30], 245]

CTM (Come to Mind)

A list is a collection of comma-separated values (items) within square brackets. Items in a list need not be of the same type.

1. Declaring/Creating Lists

Basic Syntax

List_Name = []
# Example:
L = []  
# Empty list initialization

2. List Types and Examples

Different Types of Lists

  • Empty List
  • Long Lists
  • Nested Lists
# List of integers
list = [10, 20, 30, 40]
# List with different data types
list = ["Deep", 450, 30.4, "python", -200]
# List of characters
list = ['A', 'E', 'I', 'O', 'U']
# List of strings
List = ["Delhi", "Mumbai"]
# Nested list (list containing another list)
List = [3, 4, [5, 6, 7], 8, 9, 10]
# Long list
List = [0, 1, 2, 3, 4, 5, 6, 100, 23, 45, 65, 33, 45, 6, 7, 82, 90, 100, 22, -32, 343, -20]

3. Creating List from Existing Sequence

What is a Sequence?

A sequence is a collection of items in a specific order.

Examples:

  • Strings ("hello")
  • Ranges (range(5))
  • Tuples ((1, 2, 3))

Syntax:<new_list_name> = list(sequence)

new_list = list(sequence)
Examples

String → List

l1 = list("python")
print(l1)      # ['p', 'y', 't', 'h', 'o', 'n']

Tuple → List

t = (10, 20, 30)
l2 = list(t)
print(l2)      # [10, 20, 30]

Range → List

r = range(5)
l3 = list(r)
print(l3)      # [0, 1, 2, 3, 4]

4. Creating List through User Input

Example 1: Taking numbers as list elements
user_input = input("Enter numbers separated by space: ")  
numbers = user_input.split()       # returns a list of strings
print(numbers)

Sample Input:

Enter numbers separated by space: 10 20 30 40

Output:

['10', '20', '30', '40']


>>> l1 = list(input("Enter a list of elements: "))
Enter a list of elements: 10,20,30,40
>>> l1
[' ', '1', '0', ',', '2', '0', ',', '3', '0', ',', '4', '0']
                            >>> l1 = list(input("Enter a list of elements: "))
                            Enter a list of elements: hi python
                            >>> l1
                            ['h', 'i', ' ', 'p', 'y', 't', 'h', 'o', 'n']

5. Creating from Existing List

>>> l1 = [10, 20, 30, 40, 50, 60, 70]
                              >>> l2 = l1[:]  # Copy entire list
                              >>> l2
                                [10, 20, 30, 40, 50, 60, 70]
                              >>> l3 = l2[1:4]  # Copy slice
                              >>> l3
                                [20, 30, 40]
                              >>> l4 = l1  # Reference to same list
                              >>> l4
                              [10, 20, 30, 40, 50, 60, 70]

6. Accessing List Elements

Example: L1 = [10, 20, 30, 40, 50, 60]

Positive Index

Index: 0 1 2 3 4 5

Value: 10 20 30 40 50 60

Negative Index

Index: -6 -5 -4 -3 -2 -1

Value: 10 20 30 40 50 60

>>> l1 = [10, 20, 30, 40, 50, 60]
>>> l1[3]
40
>>> l1[-3]
40
>>> l1[0]
10
>>> l1[-1]
60

>>> l1[7]  # Index out of range
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    l1[7]
IndexError: list index out of range

Traversing a List

Accessing each element of a list. This can be done with the help of for loop and while loop.

Method 1: Direct Iteration

list = ['l', 'e', 'a', 'r', 'n']
for i in list:
    print(i)

Method 2: Using range() Function

list = ['l', 'e', 'a', 'r', 'n']
n = len(list)
for i in range(n):
    print(list[i])
print("Total number of characters:", n)

Comparing Lists

L1 = [10, 20, 30, 40, 50]
L2 = [10, 20, 30, 40, 50]
L3 = [1, 2, 3]

>>> L1 == L2
True
>>> L1 == L3
False
>>> L1 > L3
True
>>> L3 > L1
False
>>> L2 < L3
False

Operations on Lists

List Operations

  • 1. Concatenation
  • 2. Repetition
  • 3. Membership Testing
  • 4. Slicing
  • 5. Indexing

1. Concatenation (+)

>>> l1 = ['red', 'blue']
>>> l2 = [10, 20, 30]
>>> l3 = l1 + ['yellow']
>>> l3
['red', 'blue', 'yellow']

>>> l4 = l1 + l2
>>> l4
['red', 'blue', 10, 20, 30]

>>> l5 = ['Green', 'white'] + ['Black']
>>> l5
['Green', 'white', 'Black']

# Error examples:
>>> l1 = l2 + 40  # TypeError: can only concatenate list (not "int") to list
>>> l1 = l2 + 'python'  # TypeError: can only concatenate list (not "str") to list

2. Repetition/Replication (*)

Multiply (*) operator replicates the list for a specified number of times and creates a new list.

>>> list1 = [10, 20, 30]
>>> list1 * 2
[10, 20, 30, 10, 20, 30]

>>> list1 * 3
[10, 20, 30, 10, 20, 30, 10, 20, 30]

>>> list1 * 4
[10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30]

>>> x = 'python' * 3
>>> x
'pythonpythonpython'

3. Membership Operators

Membership testing checks whether a particular element/item is a member of that sequence or not.

>>> x = [10, 20, 30, 40, 50, 100]
>>> print(100 in x)
True
>>> print(100 not in x)
False
>>> print(12 not in x)
True

4. Indexing

Index is the position value for each item present in the sequence.

>>> x = [10, 20, 30, 40, 50, 100]
>>> x[0]
10
>>> x[-1]
100
>>> x[4]
50

5. Slicing

>>> x = [1, 2, 3, 4, 5, 6]
>>> x[0:3]
[1, 2, 3]
>>> x[0:5]
[1, 2, 3, 4, 5]
>>> x[1:5]
[2, 3, 4, 5]
>>> x[1:5:-1]
[]
>>> x[0:5:-1]
[]
>>> x[1:3:2]
[2]
>>> x[0:5:2]
[1, 3, 5]

Nested Lists

>>> x = [1, 2, 3, [10, 20, 30, 40], 'a', 'b']
>>> x[4]
'a'
>>> x[3]
[10, 20, 30, 40]
>>> x[3][1]
20

Copying Lists

Different Methods to Copy Lists

  • Method 1: L1 == L2 (Comparison, not copying)
  • Method 2: L3 = L1[:] (Slice copy)
  • Method 3: L4 = list(L3) (Constructor copy)
  • Method 4: L5 = copy.copy(L4) (Using copy module)

List Built-in Functions and Methods

Complete List of Methods

1. append()
2. extend()
3. index()
4. insert()
5. sort()
6. sorted()
7. pop()
8. remove()
9. reverse()
10. max(), min(), sum()
11. clear()
12. len()
13. count()
14. del()

1. append()

Add item to the end of the list.

Syntax: list.append(item)

>>> l1 = [1, 2, 3, 4, 5]
>>> l1.append(100)
>>> l1
[1, 2, 3, 4, 5, 100]

>>> l1 = [1, 2, 3, 40, 67, 'a', "10+j23", "python", 20.34, 100]
>>> l1.append(99)
>>> l1
[1, 2, 3, 40, 67, 'a', '10+j23', 'python', 20.34, 100, 99]

>>> l1.append("list")
>>> l1
[1, 2, 3, 40, 67, 'a', '10+j23', 'python', 20.34, 100, 99, 'list']

>>> l1.append(10, 20)  # Error: takes exactly one argument
TypeError: append() takes exactly one argument (2 given)

2. extend()

Add one list at the end of another list. All items of a list are added at the end of an already created list.

Syntax: list1.extend(list2)

>>> l1 = [1, 2, 3, 4]
>>> l2 = [10, 20, 30]
>>> l1.extend(l2)
>>> l1
[1, 2, 3, 4, 10, 20, 30]
>>> l2
[10, 20, 30]

3. index()

Return the index of the first element whose value is equal to item. A ValueError exception is raised if item is not found in the list.

Syntax: list.index(item)

>>> l1 = [1, 2, 3, 4, 5, 100]
>>> l1.index(5)
4
>>> l1.index(50)  # Error: not found
ValueError: 50 is not in list

>>> l1 = [1, 2, 3, 4, 5, 6, 10, 40, 50]
>>> l1[7]
40
>>> l1.index(10)
6

4. insert()

Inserts item into the list at the specified index. When an item is inserted, the list expands and existing items shift by one position.

Syntax: insert(index, item)

>>> l1 = [10, 20, 30]
>>> l1.insert(1, 2200)
>>> l1
[10, 2200, 20, 30]

>>> l1.insert(4, 100)
>>> l1
[10, 2200, 20, 30, 100]

>>> l1.insert(-1, 500)
>>> l1
[10, 2200, 20, 30, 500, 100]

>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l1.insert(1, 100)
>>> l1
[1, 100, 2, 3, 4, 5, 6]

>>> l1.insert(0, 90)
>>> l1
[90, 1, 100, 2, 3, 4, 5, 6]

>>> l1.insert(len(l1), 1000)
>>> l1
[90, 1, 100, 2, 3, 4, 5, 6, 1000]

5. sort()

Sorts the items in the list in ascending order (from lowest to highest values).

Syntax: list.sort()

>>> l1 = [10, 20, 30, 100, 250, 500, 800, 2200]
>>> l1.sort()
>>> l1
[10, 20, 30, 100, 250, 500, 800, 2200]

>>> l1.sort(reverse=True)
>>> l1
[2200, 800, 500, 250, 100, 30, 20, 10]

>>> l1.sort(reverse=False)
>>> l1
[10, 20, 30, 100, 250, 500, 800, 2200]

6. sorted()

Returns a new sorted list without modifying the original list.

Syntax: sorted(list)

>>> l1 = [10, 23, 4, 6, 2, 7, 45, 67]
>>> l1.sorted()  # Error: list has no sorted method
AttributeError: 'list' object has no attribute 'sorted'

>>> sorted(l1)  # Correct usage
[2, 4, 6, 7, 10, 23, 45, 67]

7. clear()

Remove all items from the list.

Syntax: list.clear()

>>> l1 = [1, 2, 3, 4, 5]
>>> l1.clear()
>>> l1
[]

8. count()

Returns how many times an element has occurred in a list. If element is not present, returns 0.

Syntax: list.count(element)

>>> l1 = [10, 2, 1, 2, 2, 1, 1, 1, 1, 4, 3, 2, 56, 2, 2, 2]
>>> l1.count(2)
7
>>> l1.count(1)
5

9. len()

Returns the length of the list.

Syntax: len(list)

>>> l1 = [1, 2, 3, 4, 5]
>>> len(l1)
5

10. reverse()

Reverse the order of items in the list.

Syntax: list.reverse()

>>> l1 = [1, 45, 23, 89, 70, 2]
>>> l1.reverse()
>>> l1
[2, 70, 89, 23, 45, 1]

11. Updating List

Syntax: L1[index] = <new_value>

>>> l2 = [10, 20, 30]
>>> l2[2] = 23
>>> l2
[10, 20, 23]

>>> l2[0] = 100
>>> l2
[100, 20, 23]

Deletion Operations

12. pop()

Remove the last item from the list.

Syntax: list.pop()

>>> l1 = [1, 2, 3, 4, 4, 5, 5, 5, 6, 6, 6]
>>> l1.pop()
6
>>> l1
[1, 2, 3, 4, 4, 5, 5, 5, 6, 6]

>>> l1.pop()
6
>>> l1
[1, 2, 3, 4, 4, 5, 5, 5, 6]

13. remove()

Removes the first occurrence of item from the list. A ValueError exception is raised if item is not found.

Syntax: list.remove(item)

>>> l1 = [10, 20, 30, 40, 50, 60, 40]
>>> l1.remove(40)
>>> l1
[10, 20, 30, 50, 60, 40]

14. del Statement

Syntax: del list[index]

>>> l1 = [1, 2, 3, 4, 4, 5, 5, 5, 6]
>>> del l1[4]
>>> l1
[1, 2, 3, 4, 5, 5, 5, 6]

>>> del l1[6]
>>> l1
[1, 2, 3, 4, 5, 5, 6]

>>> del l1[8]  # Error: index out of range
IndexError: list assignment index out of range

15. max(), min(), sum()

>>> l1 = [2, 70, 89, 23, 45, 1]
>>> max(l1)
89
>>> min(l1)
1

>>> l1 = [2, 2, 2, 1, 1, 1, 1, 4, 3, 2, 56, 2, 2, 2]
>>> sum(l1)
81

# Mean calculation
# Mean = sum of elements / total number of elements

Practice Problems

Problem 1

Suppose L = ['abc', [6, 7, 8], 3, 'Mouse']. Consider the above list and answer the following:

  • A) L[3:1]
  • B) L[::2]
  • C) L[1:2]
  • D) L[1][1]

Problem 2

Write the output of the following:

L = []
L1 = []
L2 = []
for i in range(6, 10):
    L.append(i)
for i in range(10, 4, -2):
    L1.append(i)
for i in range(len(L1)):
    L2.append(L[i] + L1[i])
L2.append(len(L) - len(L1))
print(L2)

Solutions

Problem 1 Solutions:

  • A) L[3:1] = [] (empty list, invalid slice)
  • B) L[::2] = ['abc', 3] (every 2nd element)
  • C) L[1:2] = [[6, 7, 8]] (slice from index 1 to 2)
  • D) L[1][1] = 7 (2nd element of nested list)

Problem 2 Solution:

L = [6, 7, 8, 9], L1 = [10, 8, 6], L2 = [16, 15, 14, 1]

Related Resources

Need Help?

Join our tuition classes for personalized guidance on Python data structures.

Register for Classes →

Practice More

Try list manipulation exercises to strengthen your Python skills.

View Practical Programs →