Lists and Tuples in Python
Operations on Lists
We have seen earlier how Lists can be created and initialized. It is possible to initialize a list with nothing in it and add items later. It is possible to have heterogeneous items inside the list. It is also possible to have a list encapsulated in another list. When a list contains another list as one of its members it is called nested list.
It is possible to access the elements in a list using positive or negative indexing. Negative indexing returns the nth element from the last while positive indexing returns the nth element from the front.
#!/usr/bin/python3 # declaring empty list test = [] # list of integers primeNums = [2,3,5,7] # list of mixed type values studentData = ['john', "smith", 29, 415312, 97.89] #nested list invoice = [100.00, ["FD20", "FLAT10", "SURPRISE40"], 20, ["No Coupons Applied"]] print("Empty list test : ", test) print("Prime Numbers list : ", primeNums) print("Student Data: ", studentData) print("****Invoice*** ") print("Total Bill Amount : $", invoice[0]) print("Available coupons : ", invoice[1]) print("Applied Coupons : ", invoice[3]) print("Sales Tax : $",invoice[2]) print("second last element in studentData: ", studentData[-2]) # example for negative indexing print("Third Element in studentData: ", studentData[2]) # indexing starts from 0. So, nth item is found at n-1th location.
Output for the above program will be:
Empty list test : []
Prime Numbers list : [2, 3, 5, 7]
Student Data: ['john', 'smith', 29, 415312, 97.89]
****Invoice***
Total Bill Amount : $ 100.0
Available coupons : ['FD20', 'FLAT10', 'SURPRISE40']
Applied Coupons : ['No Coupons Applied']
Sales Tax : $ 20
second last element in studentData: 415312
Third Element in studentData: 29
Updating and Deleting List Items
It is possible to update or delete the values in a list by specifying the location where changes need to go. Alternatively, lists have built-in methods which can be used to achieve this.
- List.append(item) – appends an item to the end of the list.
- List.extend(anotherList) – appends contents of "anotherList" to the existing list.
- List.remove(item) – removes the item from the list.
- List.insert(index,data) – inserts the data at given index.
- List.pop() – removes the last element from the list. The way this function works is similar to pop operation on a stack.
Following example demonstrates how these functions can be used.
#!/usr/bin/python nums = [2,3,4,5] print("initial value of nums List") print(nums) nums[0:] = [1,3,5,7] #alters whole list as index 0 is given as starting point print("Altered Value using slice operator [0:] ") print(nums) nums.append(9) print("value after appending 9 : ", nums) nums.remove(1) print("value after removing 1 : ", nums) nums.insert(0, 2) print("value after inserting 2 : ", nums) top = nums.pop() print("popped value : ", top, ". value after popping : ", nums) testList = [11,13,17,19] nums.extend(testList) print("value after appending testList : ", nums)
Output for the above code will be:
initial value of nums List
[2, 3, 4, 5]
Altered Value using slice operator [0:]
[1, 3, 5, 7]
value after appending 9 : [1, 3, 5, 7, 9]
value after removing 1 : [3, 5, 7, 9]
value after inserting 2 : [2, 3, 5, 7, 9]
popped value : 9 . value after popping : [2, 3, 5, 7]
value after appending testList : [2, 3, 5, 7, 11, 13, 17, 19]
Important Methods of List
There are some more methods that can be handy while handling lists in Python.
- len(list) – Gives the length of the list.
- list(givenTuple) – converts a given tuple to list
- min(list) – returns the minimum value stored in the list.
- max(list) – returns the maximum value stored in the list.
- List.count(givenObj) – returns the frequency of occurrence of the "givenObj" item in the list
- List.reverse() – reverses the order in which objects are placed in the list.
- List.sort() – sorts objects in a list.
- List.index(givenObj) – performs a binary search and returns the index of the first occurrence of "givenObj" in the list.
Following example demonstrates how these functions can be used.
#!/usr/bin/python nums = [2,3,4,5,7,3] print("initial value of nums List") print(nums) print("length of nums = ", len(nums)) print("first occurrence of 3 at index ", nums.index(3)) print("minimum value stored in list = ", min(nums)) print("maximum value stored in list = ", max(nums)) print("number of times 3 occurs in the list =", nums.count(3)) print("sorted list = ", nums.sort()) print("reversed list = ", nums.reverse()) testTuple = (10, 20, 30) print("given tuple : ", testTuple) newList = list(testTuple) newList.append(1) print("newList value after appending 1 = ", newList)
Output for the above code will be:
initial value of nums List
[2, 3, 4, 5, 7, 3]
length of nums = 6
first occurrence of 3 at index 1
minimum value stored in list = 2
maximum value stored in list = 7
number of times 3 occurs in the list = 2
sorted list = None
reversed list = None
given tuple : (10, 20, 30)
newList value after appending 1 = [10, 20, 30, 1]
Operations on Tuples
Since Tuples are immutable, unlike lists, they don’t have specifically built-in functions which enable a user to modify them. But there are certain functions that are supported by tuples which are similar to len(), min(), max(), and tuple()
- Len() – gives the length of the tuple
- Min() – gives the minimum element in the tuple
- Max() – gives the maximum value in the tuple
- Tuple(givenList) – converts the given List to a tuple
© 2019 Sam Shepards
Comments
No comments yet.