7.-Lists-in-Python
7.-Lists-in-Python
Lists In Python
Python lists are containers used to store a list of values of any data type. In
simple words, we can say that a list is a collection of elements from any data
type.
In Python, lists are mutable i.e., Python will not create a new list if we modify
an element of the list.
It works as a container that holds other objects in each order. We can perform
various operations like insertion and deletion on list.
A list can be composed by storing a sequence of different type of values
separated by commas. Python list is enclosed between square [] brackets and
elements are stored in the index basis with starting index 0.
How to create a list
a = [45, 33, 22, 12]
b = ["Anirudh", 67, 89.99, -100, "Hello"]
c = []
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Output
Elements in a List
Following is the pictorial representation of a list. We can see that it allows to
access elements from both end (forward and backward).
data = [1, 2, 3, 4, 5]
Output
Output
4) Updating List
To update or change the value of index of a list, assign the value to that
index of the List.
data1 = [56, "india", "python", 45, 12, 22]
print(data1)
data1[1] = "india is great"
print(data1)
data1[3] = 99
data1[-1] = 100
print(data1)
Output
Output
6) Delete elements
In Python, del statement can be used to delete an element from the list.
It can also be used to delete all items from startIndex to endIndex.
data1 = ["india", "python", 54, 12, 78, "australia"]
print(data1)
del data1[0]
print(data1)
del data1[1:4]
print(data1)
Output
Output
Output
Output
Output
Output
Output
Output
Output
Output
data1.reverse()
print(data1)
Output
Output
Using FOR-LOOP
list1 = [56, 123, -56, 2111, 3]
for i in list1:
print(i)
Output
length = len(list1)
for i in range(length):
print(list1[i])
Output
Using IN LIST
list1 = [56, 123, -56, 2111, 3]
for i in list1:
print(i)
Output
Using WHILE-LOOP
list1 = [56, 123, -56, 2111, 3]
length = len(list1)
i = 0
Output