10_Lists in Python
10_Lists in Python
Learning objective
• Python Lists
• Accessing Values in Lists
• Updating Lists
• Deleting List Elements
• Basic List Operations
• Built-in List Functions and Methods
Lists - Introduction
• The most versatile data type available in Python
• Written as a list of csv (items) between square brackets
• Items in a list need not be of the same type
• May contain Data Types like Integers, Strings, as well as Objects.
• Lists are mutable; they can be altered even after their creation.
• Lists are ordered and have a definite count.
• The elements in a list are indexed according to a definite
sequence and the indexing of a list is done with 0 being the first
index.
Lists – introduction
• Collection of Multiple Data.
• Holds Multiple Data types.
• Lists are Mutable.
• Store multiple data at same time.
• For example:
• You can also add to elements in a list with the append() method.
Updating Lists
z = [30, 17, 40, 2]
# Update the item at index 1 with the string “python"
print(z)
z[1] = "Python"
print(z) #Output->[30, 'Python', 40, 2]
z.append(100)
#Use of append method to add 100
print(z) #Output->[30, 'Python', 40, 2, 100]
Deleting List Elements
• To remove a list element, you can use either the del statement or
remove() method.
# Repetition
list3 = [55] * 3
print(list3)
Built-in List Functions
• Python includes the following list functions:
• cmp(list1, list2) : Compares elements of both lists.
• Please note cmp() is notsupported in python 3.
list4 =["arif","vijay","said","nasser"]
print(len(list4))
print(min(list4))
print(max(list4))
nestedlist1=[[1,2],[5,7],[2,4]]
print(len(nestedlist1))
print(min(nestedlist1))
print(max(nestedlist1))
Built-in List Methods
• list.append(obj):
• Appends object obj to list
• list.count(obj):
• Returns count of how many times obj occurs in list
• list.index(obj):
• Returns the lowest index in list that obj appears
• list.insert(index, obj):
• Inserts object obj into list at offset index
• list.pop(obj=list[-1]) :
• Removes and returns last object or obj from list
Built-in List Methods
• list.remove(obj):
• Removes object obj from list
• list.reverse():
• Reverses objects of list in place
• list.sort([func]):
• Sorts objects of list, use compare func if given
• list.extend(sequence):
• Used to add all elements of a specified sequence (e.g., list, tuple, or set)
to the end of a list.
• This is different from append(), which adds the sequence itself as a single
element.
x = [1,2,3,1,4,5] x = [1,2,3,1,4,5]
print(x) x.reverse()
x.append(100) print(x)
print(x.count(1))
x.insert(2, 10) x.sort()
print(x) print(x)
x.remove(3) x.sort(reverse=True)
print(x) print(x)
print(x.index(1))
popped_element = x.pop() y=[10,20,15]
print(x) z=[30,40,50,60]
popped_element2 = x.pop(5) y.extend(z)
print(x) print(y)
# Extending list with a tuple
students = ["ahmed", "ali"]
more_students = ("yousuf", "salim")
students.extend(more_students)
print(students)