Unit 2 (First)
Unit 2 (First)
– list=[]
– print(list)
– print(type(list))
• Accessing a List : To access elements in a list, you can use the
index.
• Eg :
– # Accessing Elements
– print(my_list[0]) # This will print 1
• Try ?????
– My_list[5]
– My_list[-1]
– My_list[n-1]
– My_list[2]=‘Good’
• # Python program to access characters of five
elements of a list.
• st_list = ["Bob", "Mark", "Deepak", "Harry",
"Ivaan"]
• print(st_list[0][1])
• print(st_list[1][1])
• print(st_list[2][3])
• print(st_list[3][0])
• print(st_list[4][4])
• Slicing a List : list slicing is a common practice
and can be used both with positive indexes as
well as negative indexes.
• #access the elements of a list using negative indexing.
– Lst = [50, 70, 30, 20, 90, 10, 50]
– print(Lst[-7::])
• Eg :
– # Initialize list
– List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
• my_list.append(new_dict)
• print(my_list)
• pop() : The pop() method can remove an element from
any position in the list. If no index is specified then
pop() removes the last item in the list.
• Eg :
– myList = [1, 2, 3, 'Python', 'makes learning fun!']
– myList.pop()
– print(myList)