Lists in python
In Python, a list is a kind of container that contains collection of any kind of value.
CREATION OF LIST
List is a standard data type of Python. It is a sequence which can store values of any kind.
• List is represented by square brackets “ [ ] “
For ex -
• [ ] Empty list
• [1, 2, 3] integers list
• [1, 2.5, 5.6, 9] numbers list (integer and float)
• [ ‘a’, ‘b’, ‘c’] characters list
• [‘a’, 1, ‘b’, 3.5, ‘zero’] mixed values list
• [‘one’, ’two’, ’three’] string list
• In Python, only list and dictionary are mutable data types, rest of all the data types are
immutable data types.
For example:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
Print(list1)
Print(list2)
Initialize list
1.Initialize list using square brackets [ ]
Using [ ] we can initialize an empty list or list with some items.
For example;
a = [ ] (empty list)
a = [1, 2, 3, 'List']
print(a)
2. Using list() constructor to Initialize a List
We can use list() constructor to create and initialize the lists. list() can also convert other
iterables to list type.
For example;
# initializing empty list
a = list()
# initializing list with items
a = ([1, 2, 3])
print(a)
Traversing Python Lists
Traversing a Python list involves accessing each element within the list. The most common
methods for traversal are:
Using a for loop: This iterates directly over the elements of the list.
my_list = [10, 20, 30, 40]
for item in my_list:
print(item)
Manipulating Python Lists
Python lists are mutable, meaning their contents can be changed after creation. Various
built-in methods facilitate list manipulation:
For example;
Adding Elements:
append(element): Adds an element to the end of the list
my_list = [1, 2]
my_list.append(3)
Print (my_list)
insert(index, element):
Inserts an element at a specific index.
my_list = [1, 3]
my_list.insert(1, 2)