Python Lists¶
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets: []
L = []
print(L)
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
print(L)
- List items are ordered, changeable, and allow duplicate values.
- List items are indexed, the first item has index [0], the second item has index [1] etc.
- The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
- Since lists are indexed, lists can have items with the same value: Allow duplicates
print(L[0])
Determine the length and type of a list¶
print(len(L))
print(type(L))
Access list items¶
- List items are indexed and you can access them by referring to the index number:
- Negative indexing means start from the end.
- 1 refers to the last item, -2 refers to the second last item etc.
- You can specify a range of indexes by specifying where to start and where to end the range.
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
print(L)
print(L[:])
print(L[::])
print(L[0])
print(L[2:5])
print(L[2:])
print(L[:5])
print(L[-1])
print(L[-3:])
Change List Items¶
print(L)
L[0] = 89
print(L)
Change a Range of Item Values¶
print(L)
L[1:3] = ["Artificial Intelligence", "Deep Learning"]
print(L)
Insert Items¶
- To insert a new list item, without replacing any of the existing values, we can use the insert() method.
print(L)
L.insert(2,"Machine Learning")
print(L)
Append Items¶
- To add an item to the end of the list, use the append() method:
print(L)
L.append("Itronix")
print(L)
Extent List¶
L1 = [10,46,67]
L2 = ["Apple","Mango","Kiwi"]
L1.extend(L2)
print(L1)
print(L2)
Remove Specified Item¶
print(L)
L.remove('Python')
print(L)
Remove Specified Index¶
- If you do not specify the index, the pop() method removes the last item.
print(L)
L.pop(2)
print(L)
The del keyword also removes the specified index:
print(L)
del L[4]
print(L)
The del keyword can also delete the list completely.
print(L)
del L
print(L)
Clear the list¶
- The clear() method empties the list.
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
L.clear()
print(L)
Loop Through a List¶
- You can loop through the list items by using a for loop:
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
for item in L:
print(item)
Loop Through the Index Numbers¶
for i in range(len(L)):
print(L[i])
Print list items using while loop¶
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
i=0
while i < len(L):
print(L[i])
i = i + 1
Find Max and Min Number in List¶
L = [46,895,23,674,78,97]
print(max(L))
print(min(L))
Sort List Alphanumerically¶
L = ["orange", "mango", "kiwi", "apple", "papaya"]
L.sort()
print(L)
L = [45,9,90,53,23,89]
L.sort()
print(L)
Sort Descending¶
L = [45,9,90,53,23,89]
L.sort(reverse=True)
print(L)
By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters: According to ASCII Value¶
L = ["Orange", "mango", "Kiwi", "apple", "Papaya"]
L.sort()
print(L)
So if you want a case-insensitive sort function, use str.lower as a key function:
L = ["Orange", "mango", "Kiwi", "apple", "Papaya"]
L.sort(key = str.lower)
print(L)
Reverse Order¶
L = ["Orange", "mango", "Kiwi", "apple", "Papaya"]
L.reverse()
print(L)
Python – List Comprehension¶
- List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
#store 1 to 10 numbers in a list
L = []
for i in range(1,11):
L.append(i)
print(L)
using list comprehension
- newlist = [expression for item in iterable]
L = [i for i in range(1,11)]
print(L)
- newlist = [expression for item in iterable if condition == True]
# store multiple of 3 from 1 to 100
L = [i for i in range(1,101) if i%3==0]
print(L)
L = ["Apple","Mango","Kiwi"]
L1 = [x if x != "Mango" else "Orange" for x in L]
print(L1)
“Above is Return the item if it is not Mango, if it is Mango return Orange”.
Looping Using List Comprehension¶
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
[print(x) for x in L]
Copy a List¶
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
L1 = [1,2,3]
L2 = L1
print(L1)
print(L2)
L1[1] = 4
print(L1)
print(L2)
L1 = [1,2,3]
L2 = L1.copy()
print(L1)
print(L2)
L1[1] = 4
print(L1)
print(L2)
Another way to make a copy is to use the built-in method list().¶
L1 = [1,2,3]
L2 = list(L1)
print(L1)
print(L2)
L1[1] = 4
print(L1)
print(L2)
Join Two Lists¶
L1 = [1,2,3]
L2 = [4,5,6]
L3 = L1 + L2
print(L3)
Another way to join two lists are by appending all the items from list2 into list1, one by one:¶
L1 = [1,2,3]
L2 = [4,5,6]
for item in L2:
L1.append(item)
print(L1)
Or you can use the extend() method, which purpose is to add elements from one list to another list:¶
L1 = [1,2,3]
L2 = [4,5,6]
L1.extend(L2)
print(L1)
Count Item in a List¶
L = [10,20,30,10,40,50,10,60]
print(L.count(10))
Convert Tuple to list¶
T = (1,2,3,4,5,6)
print(T)
L = list(T)
print(L)
Remove duplicate items from list using set()¶
L = [1,2,3,1,4,6,4,5,6,8,6,7,8,9,1,5,6,3]
print(L)
L1 = set(L)
print(L1)
L1 = list(L1)
print(L1)
Multidimension List¶
L = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print(L)
print(L[0])
print(L[1])
print(L[2])
print(L[0][0])
print(L[0][1])
print(L[0][2])
print(L[0][3])
print(L[0][4])
Iterate 2D List¶
L = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
for row in L:
print(row)
L = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
for row in L:
for col in row:
print(col,end=' ')
print()
Create 1D Array¶
# First method to create a 1 D array
N = 5
arr = [0]*N
print(arr)
# Second method to create a 1 D array
N = 5
arr = [0 for i in range(N)]
print(arr)
Create 2D Array¶
# Using above first method to create a 2D array
rows, cols = (5, 5)
arr = [[0]*cols]*rows
print(arr)
# Using above second method to create a 2D array
rows, cols = (5, 5)
arr = [[0 for i in range(cols)] for j in range(rows)]
print(arr)
rows, cols = (5, 5)
arr=[]
for i in range(rows):
col = []
for j in range(cols):
col.append(0)
arr.append(col)
print(arr)
Adding a sublist using append method¶
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
a.append([5, 10, 15, 20, 25])
print(a)
a[0].extend([12, 14, 16, 18])
print(a)
a[2].reverse()
print(a)