Session-5 List in Python
Session-5 List in Python
Python Data
Python is a dynamically typed language
Types hence we need not define the type of
the variable while declaring it.
String
In python, we can use single,
double, or triple quotes to define a
string.
list
Eg. List1 = [1,2,3,4,5]
list2 = [‘a’, ’b’, ‘c’, ‘d’, ‘e’]
list3 = [1, “Name”, 1.5]
• Syntax: list_name = [ ]
• Syntax:
list_name = [L1_Value, L1_Value,
[L2_Value, L2_Value, ….]]
Eg. A=[[11, 12, 13], [21, 22, 23], [31, 32, 33]]
Printing Lists
Syntax : print(list_name)
Negative indexing
Range of index
>>> i = 0
>>> while i < len(z):
print(z[i])
i += 1
Output:
3
7
4
2 By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
Range of indexes (Slicing)
• We can specify a range of
indexes by specifying from
where to start and where to end
the range.
• We can access a range of items
in a list by using the slicing
operator : (colon).
• Slicing is used to extract a part of
the list.
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
Range of indexes (Slicing)…
• >>> list1 =['Red','Green','Blue','Cyan','Magenta','Yellow','Black']
• >>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
Changing
the Item
value
append() – This method add one item to the end of the list.
extend() - This method adds all the elements of a list to the end of the current list.
pop() – This method removes and returns an element at the given index. And removes
the last item if index is not provided.
clear() – This method removes all items from the list. i.e. empty a list.
To determine the
number of items in
a list, we use the
len() method.
a. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
b. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)
c. list1 = [1,2,3,4,5]
print(list1[len(list1)-1])
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)