15 Lecture Lists
15 Lecture Lists
c= [ 2.5, “Nit”, 24] #The elements of a list don’t have to be the same type
d= [ “Srinagar”, “Jammu”, [“JU”, “KU”, 23]] # This is nested list, i.e., list in
another list.
• A list with no elements is called as an empty list. An empty list can be
created as:
empty= []
Accessing List values or Elements
• Like Strings, the elements of Lists can be accessed using the indexes.
List_name[index]
• Indexing in a List are of two types:
1. Positive Indexing – Here the indexing starts from 0, moving from left
to right.
2. Negative Indexing – In this, the indexing starts from right to left and
the rightmost element has an index value of -1.
a = ['Hello', 1, 4.63, True, "World", 2.0, "False"]
Lists are Mutable
• Unlike Strings which are immutable, Lists are mutable which means
that the value of elements of Lists can be modified.
• you can change the order of items in a list or reassign an item in a list.
• Delete an element, add new element, update the value of an element
of a list.
For example:
a= [ 2020, “NIT Srinagar”]
a[0]=2020
print(a) #[2020,”NIT SRINAGAR”]
In operator Works in Lists
CSE2021= [ “Vikram”, “Arjun”, “Danish”]
>>> “Danish” in CSE2021
True
for item in x:
print(“hello”)
Traversing a Nested List
• A nested List contains another list as its element.
• For example: a= [“Car”, “Bike”, [“Bicycle”, “ Rikshaw”]]
for item in a:
print(item)
Although a list contain another list, the nested list still counts as a
single element.
Traversing a Nested List
How to Traverse all the elements of a List (including the nested list
element)?
Output:
How to Traverse all the elements of a List
(including the nested list element)?
a= ["Car", "Bike", ["Bicycle", "Rikshaw"]]
for item in a:
if str(type(item)).find('list')!=-1:
for i in item:
print(i)
else:
print(item)
List operations
1. + Operator: between two lists performs the concatenation of two lists.
a= [ 1, 2, 3]
b= [10, 20, 30]
C=a+b #will return [1, 2, 3, 10, 20, 30]
Pop method modifies the list and returns the element that was
removed.
x= t.pop(1)
If you don’t provide an index, it deletes and returns the last element.
Deleting elements of a List
• If you know the element you want to remove (but not the index), you
can use remove:
t.remove(10) # this will remove the first occurrence of
element 10 from the list.
if element to delete is not in list, then this method gives
“ValueError: element not in list” exception
To delete more than one values, use the del method with slice operator
del t[2:3]