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
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
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
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
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
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
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
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
In the above example, a string is read from the keyboard and each item is converted into int using map(aFunction,aSequence) function.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
More about list data structures like list comprehensions and nested lists will be explained in Chapter 3.