Lists in Python
Lists in Python
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all
types of items (including another list) in a list. A list may contain mixed type of items, this is possible
because a list mainly stores references at contiguous locations and actual items may be stored at
different locations. List can contain duplicate items. List in Python are Mutable. Hence, we can
modify, replace or delete the items. Lists are ordered. It maintains the order of elements based on
how they are added. Accessing items in List can be done directly using their position (index), starting
from 0.
# example
print(a)
Creating a List
a = [1, 2, 3, 4, 5]
# List of strings
print(a)
print(b)
print(c)
We can also create a list by passing an iterable (like a string, tuple, or another list) to list() function.
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)
We can create a list with repeated elements using the multiplication operator.
a = [2] * 5
b = [0] * 7
print(a)
print(b)
Elements in a list can be accessed using indexing. Python indexes start at 0, so a[0] will access the
first element, while negative indexing allows us to access elements from the end of the list. Like
index -1 represents the last elements of list.
print(a[0]) # ouput is 10
print(a[-1]) # output is 50
a = []
a.append(10)
print("After append(10):", a)
# Inserting 5 at index 0
a.insert(0, 5)
# Output -After extend([15, 20, 25]): [5, 10, 15, 20, 25]
a[1] = 25
print(a)
a.remove(30)
print("After remove(30):", a)
popped_val = a.pop(1)
del a[0]
We can iterate the Lists easily by using a for loop or other iteration methods. Iterating over lists is
useful when we want to do some operation on each item or access specific items based on certain
conditions. Let’s take an example to iterate over the list using for loop.
for item in a:
print(item)
Output
apple
banana
cherry
A nested list is a list within another list, which is useful for representing matrices or tables. We can
access nested elements by chaining indexes.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
Output