Python Fundamentals: Lists


Python lists are ordered collections of elements. They are mutable, which means elements of a list can be changed. We can store different types of elements in a list and access them using their index.

a. Creating a list: Lists in Python can be created by just placing the sequence inside the square brackets [ ].

Code

list1 = [1, 2, 3, 4, 5]
print(list1)

Output

[1, 2, 3, 4, 5]

b. Accessing elements in a list: We can access individual elements using indexing and a range of elements using slicing.

Code

list1 = [1, 2, 3, 4, 5]
print(list1[0])
print(list1[2:4])
print(list1[:])

Output

1
[3, 4]
[1, 2, 3, 4, 5]

c. List operations: Python includes the following list operations - appending, extending, inserting, removing elements.

Code

list1 = [1, 2, 3, 4, 5]
list1.append(6)
list1.extend([7, 8])
list1.insert(0, 0)
list1.remove(3)
print(list1)

Output

[0, 1, 2, 4, 5, 6, 7, 8]

d. List methods: Python includes the following built-in methods to manipulate lists - sort(), reverse(), count(), pop(), clear().

Code

list1 = [5, 3, 1, 4, 2]
list1.sort()
print(list1)

list1.reverse()
print(list1)

print(list1.count(3))

list1.pop()
print(list1)

list1.clear()
print(list1)

Output

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
1
[5, 4, 3, 2]
[]

Enquiries

[email protected]

Copyright © 2023 - slash-root.com