๐Ÿ“˜ MODULE II ยท SECTION 2.3

Section 2.3
LIST

Every word, example, method, and output โ€” exactly as in the textbook
๐Ÿ“‘ Table of Contents

2.3 LIST

List is an ordered sequence of items. It is one of the most used data type in Python and is very flexible. All the items in a list do not need to be of the same type. Items separated by commas are enclosed within brackets [ ]. To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indices starting at 0 in the beginning of the list and ending with -1. The plus (+) sign is the list concatenation operator and the asterisk (*) is the repetition operator.

Example Program

first_list = ['abcd',147,2.43,'Tom',74.9]
small_list = [111,'Tom']

print(first_list) # Prints complete list
print(first_list[0]) # Prints first element of the list
print(first_list[1:3]) # Prints elements starting from 2nd till 3rd
print(first_list[2:]) # Prints elements starting from 3rd element
print(small_list * 2) # Prints list two times
print(first_list + small_list) # Prints concatenated lists

Output

['abcd',147,2.43,'Tom',74.9] abcd [147,2.43] [2.43,'Tom',74.9] [111,'Tom',111,'Tom'] ['abcd',147,2.43,'Tom',74.9,111,'Tom']

We can update lists by using the slice on the left hand side of the assignment operator. Updates can be done on single or multiple elements in a list.

Example Program

Demo of List Update

list = ['abcd',147,2.43,'Tom',74.9]
print("Item at position 2=",list[2])
list[2]=500
print("Item at position 2=",list[2])
print("Item at Position 0 and 1 is",list[0],list[1])
list[0]=20;list[1]='apple'
print("Item at Position 0 and 1 is", list[0], list[1])

Output

Item at position 2= 2.43 Item at position 2= 500 Item at Position 0 and 1 is abcd 147 Item at Position 0 and 1 is 20 apple

To remove an item from a list, there are two methods. We can use del statement or remove() method which will be discussed in the subsequent session.

Example Program

#Demo of List Deletion
list = ['abcd', 147, 2.43, 'Tom', 74.9]
print(list)
del list[2]
print("List after deletion: ", list)

Output

['abcd', 147, 2.43, 'Tom', 74.9] List after deletion: ['abcd', 147, 'Tom', 74.9]

2.3.1 Built-in List Functions

1. len(list) - Gives the total length of the list.

Example Program

#Demo of len(list)
list1 = ['abcd', 147, 2.43, 'Tom']
print(len(list1))

Output

4

2. max(list) - Returns item from the list with maximum value.

Example Program

#Demo of max(list)
list1 = [1200, 147, 2.43, 1.12]
list2 = [213, 100, 289]
print("Maximum value in: ", list1, "is", max(list1))
print("Maximum value in: ", list2, "is", max(list2))

Output

Maximum value in: [1200, 147, 2.43, 1.12] is 1200 Maximum value in: [213, 100, 289] is 289

3. min(list) - Returns item from the list with minimum value.

Example Program

#Demo of min(list)
list1 = [1200, 147, 2.43, 1.12]
list2 = [213, 100, 289]
print("Minimum value in: ", list1, "is", min(list1))
print("Minimum value in: ", list2, "is", min(list2))

Output

Minimum value in: [1200, 147, 2.43, 1.12] is 1.12 Minimum value in: [213, 100, 289] is 100

4. list(seq) - Returns a tuple into a list.

Example Program

#Demo of list(seq)
tuple = ('abcd', 147, 2.43, 'Tom')
print("List:", list(tuple))

Output

List: ['abcd', 147, 2.43, 'Tom']

5. map(aFunction,aSequence) - One of the common things we do with list and other sequences is applying an operation to each item and collect the result. The map(aFunction,aSequence) function applies a passed-in function to each item in an iterable object and returns a list containing all the function call results.

Example Program

str=input("Enter a list(space separated):")
lis=list(map(int,str.split()))
print(lis)

Output

Enter a list(space separated):1 2 3 4 [1, 2, 3, 4]

In the above example, a string is read from the keyboard and each item is converted into int using map(aFunction,aSequence) function.


2.3.2 Built-in List Methods

1. list.append(obj) - This method appends an object obj passed to the existing list.

Example Program

#Demo of list.append(obj)
list = ['abcd', 147, 2.43, 'Tom']
print("Old List before Append:", list)
list.append(100)
print("New List after Append:", list)

Output

Old List before Append: ['abcd', 147, 2.43, 'Tom'] New List after Append: ['abcd', 147, 2.43, 'Tom', 100]

2. list.count(obj) - Returns how many times the object obj appears in a list.

Example Program

#Demo of list.count(obj)
list = ['abcd', 147, 2.43, 'Tom', 147, 200, 147]
print("The number of times", 147, "appears in", list, "=", list.count(147))

Output

The number of times 147 appears in ['abcd', 147, 2.43, 'Tom', 147, 200, 147] = 3

3. list.remove(obj) - Removes object obj from the list.

Example Program

#Demo of list.remove(obj)
list1 = ['abcd', 147, 2.43, 'Tom']
list1.remove('Tom')
print(list1)

Output

['abcd', 147, 2.43]

4. list.index(obj) - Returns index of the object obj if found, otherwise raise an exception indicating that value does not exist.

Example Program

#Demo of list.index(obj)
list1 = ['abcd', 147, 2.43, 'Tom']
print(list1.index(2.43))

Output

2

5. list.extend(seq) - Appends the contents in a sequence seq passed to a list.

Example Program

#Demo of list.extend(seq)
list1 = ['abcd', 147, 2.43, 'Tom']
list2 = ['def', 100]
list1.extend(list2)
print(list1)

Output

['abcd', 147, 2.43, 'Tom', 'def', 100]

6. list.reverse() - Reverses objects in a list.

Example Program

#Demo of list.reverse()
list1 = ['abcd', 147, 2.43, 'Tom']
list1.reverse()
print(list1)

Output

['Tom', 2.43, 147, 'abcd']

7. list.insert(index,obj) - Returns a list with object obj inserted at the given index.

Example Program

#Demo of list.insert(index,obj)
list1 = ['abcd', 147, 2.43, 'Tom']
print("List before insertion:", list1)
list1.insert(2,222)
print("List after insertion:", list1)

Output

List before insertion: ['abcd', 147, 2.43, 'Tom'] List after insertion: ['abcd', 147, 222, 2.43, 'Tom']

8. list.sort([Key=None,Reverse=False]) - Sorts the items in a list and returns the list. If a function is provided, it will compare using the function provided.

Example Program

#Demo of list.sort([Key=None,Reverse=False])
list1 = [890, 147, 2.43, 100]
print("List before sorting:", list1)
list1.sort()
print("List after sorting in ascending order:", list1)

Output

List before sorting: [890, 147, 2.43, 100] List after sorting in ascending order: [2.43, 100, 147, 890]

The following example illustrates how to sort the list in descending order.

Example Program

#Demo of list.sort([Key=None,Reverse=False])
list1 = [890, 147, 2.43, 100]
print("List before sorting:", list1)
list1.sort(reverse=True)
print("List after sorting in descending order:", list1)

Output

List before sorting: [890, 147, 2.43, 100] List after sorting in descending order: [890, 147, 100, 2.43]

9. list.pop([index]) - Removes or returns the last object obj from a list. We can even pop out any item in a list with the index specified.

Example Program

#Demo of list.pop([index])
list1 = ['abcd', 147, 2.43, 'Tom']
print("List before popping:", list1)
list1.pop(-1)
print("List after popping:", list1)
item=list1.pop(-3)
print("Popped item:", item)
print("List after popping:", list1)

Output

List before popping: ['abcd', 147, 2.43, 'Tom'] List after popping: ['abcd', 147, 2.43] Popped item: 147 List after popping: ['abcd', 2.43]

10. list.clear() - Removes all items from a list.

Example Program

#Demo of list.clear()
list1 = ['abcd', 147, 2.43, 'Tom']
print("List before clearing:", list1)
list1.clear()
print("List after clearing:", list1)

Output

List before clearing: ['abcd', 147, 2.43, 'Tom'] List after clearing: []

11. list.copy() - Returns a copy of the list

Example Program

#Demo of list.copy()
list1 = ['abcd', 147, 2.43, 'Tom']
print("List before clearing:", list1)
list2=list1.copy()
list1.clear()
print("List after clearing:", list1)
print("Copy of the list:", list2)

Output

List before clearing: ['abcd', 147, 2.43, 'Tom'] List after clearing: [] Copy of the list: ['abcd', 147, 2.43, 'Tom']

2.3.3 Using List as Stacks

The list can be used as a stack (Last IN First Out). Stack is a data structure where the last element added is the first element retrieved. The list methods make it very easy to use a stack. To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.

Example Program

#Demo of List as Stack
stack=[10,20,30,40,50]
stack.append(60)
print("Stack after appending:", stack)
stack.pop()
print("Stack after popping:", stack)

Output

Stack after appending: [10, 20, 30, 40, 50, 60] Stack after popping: [10, 20, 30, 40, 50]

2.3.4 Using List as Queues

It is also possible to use a list as a queue, where the first element added is the first element retrieved. Queues are Last In First Out (LIFO) data structure. But lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow since all of the other elements have to be shifted by one.

To implement a queue, Python provides a module called collections in which a method called deque is designed to have fast appends and pops from both ends.

Example Program

#Demo of List as Queue
from collections import deque
queue = deque(["apple", "orange", "pear"])
queue.append("cherry") # cherry arrives
queue.append("grapes") # grapes arrives
queue.popleft() # The first to arrive now leaves
queue.popleft() # The second to arrive now leaves
print(queue) # Remaining queue in order of arrival

Output

deque(['pear', 'cherry', 'grapes'])

More about list data structures like list comprehensions and nested lists will be explained in Chapter 3.


๐Ÿ“Œ Summary of Section 2.3