Working with list
List literals are enclosed within square brackets. A list can store data in the form of a string literal, integer or any allowed data type in Python. The first element of the list can be accessed using index 0. We can traverse a list using for loop and can process or manipulate the individual element stored in the list. There are different methods or operations that can be performed on the list such as append, insert, extend, index, remove, sort, reverse, pop. We will also discover the use of an empty list. A list can also be used as a single dimensional array or multi-dimensional array.
STORE ITEMS, TRAVERSE LIST, ACCESS USING INDEX
The following code demonstrates how to store items in a list, how to traverse a list, how to access elements of a list using index.
Code:
Nordic_Country_List = ["FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS"]
Asian_Country_List = ["CHINA", "INDIA", "INDONESIA", "PAKISTAN", "BANGLADESH", "JAPAN", "PHILIPPINES", "VIETNAM"]
for i in Nordic_Country_List:
print(i, end=" ")
print("\n")
for i in Asian_Country_List:
print(i, end=" ")
print("\n")
#Lets calculate the size of the List
#Then we access element of List using index
Nordic_length = len(Nordic_Country_List)
Asian_length = len(Asian_Country_List)
for i in range(Nordic_length):
print(Nordic_Country_List[i], end=" ")
print("\n")
for i in range(Asian_length):
print(Asian_Country_List[i], end=" ")
Output:
FINLAND ICELAND NORWAY DENMARK SWEDEN FAROE ISLANDS CHINA INDIA INDONESIA PAKISTAN BANGLADESH JAPAN PHILIPPINES VIETNAM FINLAND ICELAND NORWAY DENMARK SWEDEN FAROE ISLANDS CHINA INDIA INDONESIA PAKISTAN BANGLADESH JAPAN PHILIPPINES VIETNAM
Append, Insert, Extend, Index, Remove, Sort, Reverse, Pop.
Syntax:
list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original. list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right. list.extend(list2) -- adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend(). list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError). list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present) list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is preferred.) list.reverse() -- reverses the list in place (does not return it) list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).
Code:
Asian_Country_List = ["CHINA", "INDIA", "INDONESIA", "PAKISTAN", "BANGLADESH", "JAPAN", "PHILIPPINES", "VIETNAM"]
#append element at end of list
Asian_Country_List.append('Thailand')
print(Asian_Country_List)
#insert element at index 0
Asian_Country_List.insert(0, 'Malaysia')
print(Asian_Country_List)
#add list of elements at end
Asian_Country_List.extend(['North Korea', 'South Korea'])
print(Asian_Country_List)
print(Asian_Country_List.index('INDONESIA'))
#search and remove that element
Asian_Country_List.remove('BANGLADESH')
print(Asian_Country_List)
#Remove third element in the list
Asian_Country_List.pop(2)
print(Asian_Country_List)
#sorts the list in place (does not return it)
Asian_Country_List.sort()
print(Asian_Country_List)
#reverses the list in place (does not return it)
Asian_Country_List.reverse()
print(Asian_Country_List)
Output:
['CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'BANGLADESH', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand'] ['Malaysia', 'CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'BANGLADESH', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand'] ['Malaysia', 'CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'BANGLADESH', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand', 'North Korea', 'South Korea'] 3 ['Malaysia', 'CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand', 'North Korea', 'South Korea'] ['Malaysia', 'CHINA', 'INDONESIA', 'PAKISTAN', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand', 'North Korea', 'South Korea'] ['CHINA', 'INDONESIA', 'JAPAN', 'Malaysia', 'North Korea', 'PAKISTAN', 'PHILIPPINES', 'South Korea', 'Thailand', 'VIETNAM'] ['VIETNAM', 'Thailand', 'South Korea', 'PHILIPPINES', 'PAKISTAN', 'North Korea', 'Malaysia', 'JAPAN', 'INDONESIA', 'CHINA']
Empty List
One popular trick is to use an empty list [] and use an “append” or “extend” method to add elements to the list.
Code:
Nordic_Country_List = ["FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS"]
Asian_Country_List = ["CHINA", "INDIA", "INDONESIA", "PAKISTAN", "BANGLADESH", "JAPAN", "PHILIPPINES", "VIETNAM"]
Country_List = []
for i in range(0, 5):
Country_List.append(Asian_Country_List[i])
print(Country_List)
Country_List_2 = []
Country_List_2.extend(Nordic_Country_List)
print(Country_List_2)
Country_List_3 = []
Country_List_3.extend(["CHINA", "INDIA", "INDONESIA"])
print(Country_List_3)
Output:
['CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'BANGLADESH'] ['FINLAND', 'ICELAND', 'NORWAY', 'DENMARK', 'SWEDEN', 'FAROE ISLANDS'] ['CHINA', 'INDIA', 'INDONESIA']
List Slices
Slices work on lists just as with strings, and can also be used to change sub-parts of the list.
Code:
Nordic_Country_List = ["FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS"] Asian_Country_List = ["CHINA", "INDIA", "INDONESIA", "PAKISTAN", "BANGLADESH", "JAPAN", "PHILIPPINES", "VIETNAM"] #Replacing first two items in the list with "GREENLAND" Nordic_Country_List[0:1] = ["GREENLAND"] print(Nordic_Country_List) #Replacing first three items in the list with TWO ITEMS "GREENLAND" and "IRELAND" Nordic_Country_List[0:2] = ["GREENLAND", "IRELAND"] print(Nordic_Country_List) #Replacing first four items in the list with TWO ITEMS "GREENLAND" and "IRELAND" Nordic_Country_List[0:4] = ["GREENLAND", "IRELAND"] print(Nordic_Country_List)
Output:
['GREENLAND', 'ICELAND', 'NORWAY', 'DENMARK', 'SWEDEN', 'FAROE ISLANDS'] ['GREENLAND', 'IRELAND', 'NORWAY', 'DENMARK', 'SWEDEN', 'FAROE ISLANDS'] ['GREENLAND', 'IRELAND', 'SWEDEN', 'FAROE ISLANDS']
Negative indexes in List
We can use negative indexes to access the list elements from the end. -1 to access the last element, -2 to access second last and so on.
Using Positive index 0 to n-1 from first to the last element. Using Negative index -1 to -n from the last element to the first.
In the below code, we will demonstrate, how to initialize a tuple and traverse the list using a for loop.
a = [1, 2, 3, 4, 5, 6]
a_length = -len(a)
for i in range(-1, a_length-1, -1):
print(a[i])
Output:
6 5 4 3 2 1
Multidimensional List
We can use nest lists within lists. With the help of a single-dimensional list, we can use the concept of an array. Similarly using the concept of a Multidimensional list we can use the concept of Multidimensional array.
Code:
a = [1, 2, 3] # 1Dimensional LIST of order 1 by 3
b = [5, 6, 6] # 1Dimensional LIST of order 1 by 3
c = [102, 5, -7] # 1Dimensional LIST of order 1 by 3
x1 = [[1, 2, 4], [2, 4, 5], [0, 0, 0]] # 2Dimensional LIST of order 3 by 3
x2 = [[5, 6, 7], [11, 14, 45], [90, 87, 73]] # 2Dimensional LIST 3 by 3
x3 = [[7, 11, 19], [15, 154, 415], [190, 807, 723]] # 2Dimensional LIST 3 by 3
d = [a, b, c] # 2Dimensional LIST of order 3 by 3
#D1 D2
D1 = len(d)
D2 = len(d[0])
for i in range(D1):
for j in range(D2):
print(d[i][j], end=" ")
print("\t")
print("\n")
x = [x1, x2, x3] # 3Dimensional LIST of order 3 by 3 by 3
#X1 X2
X1 = len(x)
X2 = len(x[0])
X3 = len(x[0][0])
for i in range(X1):
for j in range(X2):
for k in range(X3):
print(x[i][j][k], end=" ")
print("\t")
print("\n")
Output:
1 2 3 5 6 6 102 5 -7 1 2 4 2 4 5 0 0 0 5 6 7 11 14 45 90 87 73 7 11 19 15 154 415 190 807 723