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:
# 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.
# Accessing elements by index
fruits = ["apple", "banana", "orange"]
[o] [1] [2]
print(fruits[0])
print(fruits[2])
Output:
apple
orange
Modifying Elements:
Let's modify our list, replacing banana with kiwi.
fruits[1] = "kiwi"
print(fruits)
Output:
['apple', 'kiwi', 'orange']
Adding Elements:
Let's add some more fruits to the list. We can use append() method.
fruits.append("watermelon") # Add to the end of the list
print(fruits)
Output:
['apple', 'kiwi', 'orange', 'watermelon']
Removing Elements:
Use remove() or pop() methods for removing elements from a list by value or index respectively.
fruits.remove("orange")
or
fruits.pop(1)
print(fruits)
Output:
['apple', 'kiwi', 'watermelon']
Length of a list:
Want to check how many elements are in your list? Use len() function.
print(len(fruits))
Output:
3
Nested list:
List can contain other lists too! This is called nested list.
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:
6