This section provides a brief overview of
You can use lists to store a sequence of values. A list is a collection of references to Python data objects. Note than in Python list indexes start at 0 (similar to C or C++). Different ways of creating lists are shown below
a = [] # creates an empty list
a = [8, 9, 10] # creates a list of three elements
b = [10, 7, 18, "Avi"]
List indices start at 0 from left with positive index. List indices start at -1 from right for negative index.
a[1] # Prints the second element
a[-2] # Prints the second element
You can access sub-lists through the colon operator. This process is called slicing.
a = [10, 7, 14, 27, 21]
a[2:] # Prints everything to the right of 14 and includes 14
a[:3] # Prints everything to the left of 27
a[2:4] # Prints sub-lists containing second and third index
a[2:-1] # Same output as above
The symbol + and * are concatenation operators. There are several methods associated with lists.
a = [10, 7, 14]
a = a*2 # output should be [10, 7, 14, 10, 7, 14]
print(a)
c = [a]*2 # Note the difference
print(c)
a = [10, 7, 14]
b = [5, 8, 11]
a = a + b # output should be [10, 7, 14, 5, 8, 11]
print(a)
len(a) #prints the length of the list
a.append(20) #Adds 20 to the end of the list
a
a.pop() # Deletes the last element
a
a.reverse() # reverses the list
a
a.sort() #sorts the list
a
a.remove(11) # removes 11
a
20 in a # Returns a boolean value for the check if element 20 is in list b
10 in a
range(start, stop, stepsize) can be used to generate a sequence of numbers. list(range(start, stop, stepsize)) can be used to create a list comprising from the sequence. Note that the number corresponding to stop is not a part of the list.
a = list(range(10,20,2))
a
You can create lists of non-integer objects also.
cities= ["Nashville", "Austin", "Pittsburgh"]
cities
Lists can contain objects of different type.
d = [5, 6, "seven", 8, 9]
d
del d[2] #removes the third element
d
Lists are a collection of references to Python data objects.
a = [5, 8 , 12]
b = a
print("a = ", a) # output is [5, 8, 12]
print("b = ", b) # output is [5, 8, 12]
a.append(4)
print("a = ", a) # output is [5, 8, 12, 4]
print("b = ", b) # output is [5, 8, 12, 4]
When we run the command
a = [5, 8 , 12]
b = a
We are essentially creating two references.
a.append(4)
print("a = ", a)
print("b = ", b)
You can use the slicing operator to make independent copies.
a = [5, 8 , 12]
b = a[:]
print("a = ", a) # output is [5, 8, 12]
print("b = ", b) # output is [5, 8, 12]
a.append(4)
print("a = ", a) # output is [5, 8, 12, 4]
print("b = ", b) # output is [5, 8, 12]
Another way is to use the deepcopy command.
from copy import deepcopy
a = [5, 8 , 12]
b = deepcopy(a)
print("a = ", a) # output is [5, 8, 12]
print("b = ", b) # output is [5, 8, 12]
a.append(4)
print("a = ", a) # output is [5, 8, 12, 4]
print("b = ", b) # output is [5, 8, 12]
Lists can be two dimensional.
twodlist = [[1, 2, 3],[11, 12, 13],[21, 22, 23]]
twodlist[1]
twodlist[1][1]
Similarly, we can define three, four, or five dimensional lists. Be careful, when you use * to create two D lists as you are creating references and not copies
b = [1,2]
A = [b]*3
print(A)
b[0] = 5
A[0][1] = 3
print(A)
Pay close attention to how the list A has changed.
Tuples are like lists but with two main differences:
Tuples are faster than lists. However, the speed gains might not be significant for our applications. Therefore, stick to lists whenever possible.
e = (3, 8, 11, 7) # creates a tuple
e
e[2] # we use square brackets to access elements of tuples
e[2] = 12 # There should be an error message
Dictionaries can be used to create maps or unordered collection of objects in Python. In dictionaries, keys are associated with values. The keys are separated from their values using colon. Each key-value item is separated using comma.
pop = {'Nashville': 200, 'Austin': 500, 'Pittsburgh': 300}
pop.keys()
pop.values()
The keys and values can be converted to lists using list() function.
list(pop.keys())
pop['Nashville']
'Austin' in pop
For loops can be used to iterate over elements in lists, tuples, or dictionaries. Indents used to identify code blocks.
a = [1, 3, 5, 7]
for i in a: # For each element in list a
print(i*i)
for i in range(20, 30):
if (i % 2 == 0):
print(i)
For loops can be nested.
for i in range(1, 5):
for j in range(10,15):
print(i*j)
When you are dealing with non-numeric lists or list lengths which keep changing during implementation you can use range(len(listname)).
cities = ["Nashville", "Austin", "Morgantown", "Portland"]
for i in range(len(cities)):
print(i,cities[i])
Another way is using enumerate.
cities = ["Nashville", "Austin", "Morgantown", "Portland"]
for num, name in enumerate(cities):
print(num, name)
If you want the index to start from a number other than 0.
cities = ["Nashville", "Austin", "Morgantown", "Portland"]
for num, name in enumerate(cities, 1):
print(num, name)
The zip command can be used to pairwise merge lists of equal lengths.
a = [1, 2, 3]
b = [10, 11, 12]
c = zip(a,b)
print(list(c))
If you want to go through two lists in a for loop.
cities = ["Nashville", "Austin", "Morgantown", "Portland"]
population = [200, 500, 100, 400]
for name, popul in zip(cities,population):
print(name, popul)
In dictionaries, the default is to iterate through the keys.
pop = {'Nashville': 200, 'Austin': 500, 'Pittsburgh': 300}
for i in pop:
print(i)
for i in pop.values():
print(i)
for i,j in pop.items():
print(i,j)
For loops and conditional expressions can be used to create lists conveniently. This is called list comprehension.
a = [i for i in range(3)]
a
a = [i*2 for i in [10, 20, 25]]
a
a = [[i,j] for i in [1, 2, 3] for j in [10, 11, 12]]
a
a = [i for i in range(5) if(i%2 == 0)]
a
c = [20, 10, 50]
d = [ 5, 25, 40]
e = [max(i) for i in zip(c,d)]
e