Lists
Lists
CS101
Introduction
• The most basic data structure in Python is the sequence.
• Each element of a sequence is assigned a number - its position or
index. The first index is zero, the second index is one, and so forth.
• The most common built-in data structures in python are lists ,
dictionaries, sets and tuples
• There are certain things you can do with all the sequence types.
• These operations include indexing, slicing, adding, multiplying, and
checking for membership.
• In addition, Python has built-in functions for finding the length of a
sequence and for finding its largest and smallest elements.
Python lists
• The list is the most versatile datatype available in Python, which can
be written as a list of comma-separated values (items) between
square brackets.
• Important thing about a list is that the items in a list need not be of
the same type.
Examples
• Creating a list is as simple as putting different comma-separated
values between square brackets.
• For example
• list1 = ['physics', 'chemistry', 1997, 2000]
• list2 = [1, 2, 3, 4, 5,6.78,0.9999,’D’]
• list3 = ["a", "b", "c", "d"];
• LIST4=[]
Accessing values of list
• To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index.
• For example-
list1 = ['physics', 'chemistry', 1997, 2000]
0 1 2 3
list2 = [1, 2, 3, 4, 5, 6, 7 ]
0 12 3 4 5 6
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
Print(list1[1,-1])
• Output:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
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.
• For example-
list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : ", list[2])
list[2] = 2001
print ("New value available at index 2 : ", list[2])
• Output:
Value available at index 2 : 1997
Deleting elements from list
• To remove a list element:
• you can use either the del statement if you know exactly which element(s) you are
deleting.
• You can use the remove() method if you do not know exactly which items to delete.
• For example-
list = ['physics', 'chemistry', 1997, 2000]
print (list)
del list[2]
print ("After deleting value at index 2 : ", list)
• Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000]
Operations on lists
Python Results Description