Py Slides 4
Py Slides 4
Python - Lists
• The list is a most versatile datatype available in Python,
which can be written as a list of comma-separated values
(items) between square brackets.
• Good thing about a list that items in a list need not all
have the same type:
• For example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
Print(list1))
list1.append(“Maths")
print “After adding New value list is: "
Print(list1))
This will produce following result:
['physics', 'chemistry', 1997, 2000]
After adding New value list is:
['physics', 'chemistry', 1997, 2000,’Maths’]
Updating Lists:
• You can update single or multiple elements of lists by giving
the slice on the left-hand side of the assignment operator, and
you can add to elements in a list with the append() method:
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list1[2];
list1[2] = 2001;
print "New value available at index 2 : "
print list1[2];
• This will produce following result:
Value available at index 2 :
1997
New value available at index 2 :
2001
Delete List Elements:
• To remove a list element, you can use either the del
statement if you know exactly which element(s) you are
deleting or the remove() method if you do not know.
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;
• This will produce following result:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
list1 = ['physics', 'chemistry', 1997, 2000];
print list1;
List1.remove(1997);
print "After deleting an element : "
print list1;
• You can loop through the list items by using a for loop
SN Function Description
1 append() Adds an element at the end of
the list
2 clear() Removes all the elements from
the list
3 copy() Returns a copy of the list
4 count() Returns the number of
elements with the specified
value
5 extend() Add the elements of a list (or
any iterable), to the end of the
current list
S
Methods with Description
N
1 index() Returns the index of the first
element with the specified value
• my_set = {1, 2, 3, 3}
• # Adding an element 4 to the set
my_set.add(4)
• print (my_set)
• my_set = {1, 2, 3, 4}
• # Removes the element 3 from the set
• my_set.remove(3)
• print (my_set)
• my_set = {1, 2, 3, 4}
• if 2 in my_set:
• print("2 is present in the set")
• else:
• print("2 is not present in the set")
• Following is the output of the above code
−
• 2 is present in the set
Set Operations
• {2,4,6,8,10}
Frozen Sets