...

/

Basic List Operations

Basic List Operations

Learn about basic list operations in Python.

Some basic list operations are given below.

Mutability

Unlike strings, lists are mutable (changeable). Lists can be updated, as shown below:

Press + to interact
Python 3.8
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
ages = [25, 26, 25, 27, 26, 28, 25]
animals[2] ='Rhinoceros'
print(animals)
ages[5] = 31
print(ages)
ages[2:5] = [24, 25, 32] # sets items 2 to 4 with values 24, 25, 32
print(ages)
ages[2:5] = [ ] # delete items 2 to 4
print(ages)

Concatenation

One list can be concatenated (appended) at the end of another, as shown below:

Press + to interact
Python 3.8
lst = [12, 15, 13, 23, 22, 16, 17]
lst = lst + [33, 44, 55]
print(lst) # prints [12, 15, 13, 23, 22, 16, 17, 33, 44, 55]

Merging

Two lists can be merged to create a new list, as shown below:

Press + to interact
Python 3.8
s = [10, 20, 30]
t = [100, 200, 300]
z = s + t
print(z) # prints [10, 20, 30, 100, 200, 300]

Conversion

A string, tuple, or set can be converted into a list using the ...