Table of Content

List



In Python, a list is a collection of items that can hold different data types. Lists are mutable, which means you can modify their elements after creation. Lists are created using square brackets [ ] and each element is separated by a comma.

Here are some examples of using lists in Python:


Creation and Initialization:

python
# Creating a list
fruits = ["apple", "banana", "orange"]

Accessing Elements:

There are different ways we can access the list in python. Below, we access the list using index.

python
# Accessing elements by index
fruits = ["apple", "banana", "orange"]
            [o]       [1]       [2]

print(fruits[0])
print(fruits[2])

Output:

python
apple
orange

Modifying Elements:

Let's modify our list, replacing banana with kiwi.

python
fruits[1] = "kiwi"
print(fruits)

Output:

python
['apple', 'kiwi', 'orange']

Adding Elements:

Let's add some more fruits to the list. We can use append() method.

python
fruits.append("watermelon") # Add to the end of the list
print(fruits)

Output:

python
['apple', 'kiwi', 'orange', 'watermelon']

Removing Elements:

Use remove() or pop() methods for removing elements from a list by value or index respectively.

python
fruits.remove("orange")
or
fruits.pop(1)
print(fruits)

Output:

python
['apple', 'kiwi', 'watermelon']

Length of a list:

Want to check how many elements are in your list? Use len() function.

python
print(len(fruits))

Output:

python
3

Nested list:

List can contain other lists too! This is called nested list.

python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2])

In this example, matrix is a nested list containing three inner lists, each representing a row of a matrix. Let's break down what each part of this nested list represents:

  • matrix[0] refers to the first inner list [1, 2, 3]. This list represents the first row of the matrix.
  • matrix[1] refers to the second inner list [4, 5, 6], representing the second row of the matrix.
  • matrix[2] refers to the third inner list [7, 8, 9], representing the third row of the matrix.

Output:

python
6