The term array in computer science means a collection of like datatypes which are indexed. Python doesn't care about the 'like datatypes' bit!
We looked at arrays when we talked about strings.
In Python, the concept of arrays is subdivided into several parts. Python has several data structures to deal with arrays.
We will focus on lists in this course.
caf_specials = [ 'breakfast sandwich', 'milk', 'rice', 'pizza', 'salad', 'fish and chips' ]
Well, now you can begin to worry about it!
Just kidding ... lists are easy to understand. They hold a series of data, and they have an index so you can access the data. In Python, you can mix the datatypes in a list.
list1 = ['dogs', 'cats', 2, 1] # a mixed list of strings and numbers
list2 = [1, 2, 3, 4, 5 ] # a list of numbers
list3 = ['a', 'b', 'c', 'd'] # a list of strings
list1 = ['dogs', 'cats', 2, 1] # a mixed list of strings and numbers
list2 = [1, 2, 3, 4, 5 ] # a list of numbers
list3 = ['a', 'b', 'c', 'd'] # a list of strings
print(list1[0]) # read from the list using a hard-coded value
i = 2
print(list1[i]) # read from the list use a variable
list1[3] = 'hamster' # write to the list using a hard-coded value
list1[i] = 'bird' # write to the list using a variable
print(list1) # this gives us proof of output, but it might not be in a user friendly format.
# it still looks like a list.
Please refer to the slicing note in the string unit.
Lists start at index 0, they support indexing, slicing, + (concatenation), * (repetition / multiplying), and negative number indexing.
list3 = ['a', 'b', 'c', 'd']
list2 = [1, 2, 3, 4, 5 ]
list3 = list3 * 2 # repetition
print(list3)
list3 = list3 + list2 # concatenation
print(list3)
print(list3[0:5]) # slicing
print(list2[-1]) # indexing, specifically: negative number indexing
list3 = ['a', 'b', 'c', 'd']
list2 = [1, 2, 3, 4, 5 ]
del(list3[0]) # Remove an item or a slice from a list
print(list3)
print(len(list2)) # length of list
print('b' in list3) # check for membership
for i in list3: # use for loop counter to access elements
print(i)
list3 = ['a', 'b', 'c', 'd']
list2 = [1, 2, 3, 4, 5 ]
list4 = ['z', '2', 'g', '1', 'a']
list3.append('qq') # add an item to the end of the list
print(list3)
list3.extend(['ww','tt']) # add a series of elements to the list
print(list3)
list3.insert(4, 'yyyyy') # Insert an item at a given position.
print(list3) # The first argument is the index of the
# element before which to insert
list3.remove('ww') # Remove the first item from the list that matched
print(list3)
list3.pop(0) # Remove the item at the given position in the list, and return it.
print(list3) # If no index is specified, a.pop() removes and returns the last item in the list.
list2.clear() # Equivalent to del
print(list3)
print(list3.index('qq')) # Return the index of the first item provided
print(list3.count('qq')) # Return the number of times item appears
list4.sort() # Sort the items of the list. Items must be of like type
print(list4)
list4.reverse() # Reverse the elements of the list
print(list4)
list2 = list4.copy() # shallow copy of list ... yes, there's a deepcopy() too
print(list2)
# This looks like a copy, and it works, but not the way you might think
foo = [1,2,3]
boo = foo
boo.pop()
print(boo)
print(foo)
#If you manipulate either foo or boo, they'll both change because they are referencing the same (one, singular, 1) list
#use copy() to make a shallow copy of your list
original = [1,2,3]
clone = original.copy()
clone.pop()
print(clone)
print(original)
This isn't part of your course, but the idea is too cool not to explore at least a little bit:
From: https://en.wikipedia.org/wiki/Stack_(abstract_data_type) :
In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed. The order in which elements come off a stack gives rise to its alternative name, LIFO (for last in, first out).
From Python's Documentation: 5.1.1 Using Lists as Stacks
The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). 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. For example:
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
Cool, eh?
Understanding Lists in Python 3 is also a good resource.
myArray = [1,2,3]
def foo(a): # a is a copy of myArray
a[0] = 99 # modify a
a[1] = 11
print(a, id(a)) # print the copy to see the change
def moo():
a[0] = 88 # crash
print(a) # crash
def doo():
myArray[0] = 77 # modify the original
print(myArray, id(myArray)) # print the original to see the change
# Passing the array to the function
print(myArray, id(myArray)) # print the original array
foo(myArray) # pass the array to a function
# now that the function is closed:
print(myArray, id(myArray)) # print the original array, CHANGES REMAIN
# Accessing the copy array without passing it
#moo() # uncomment this line to see what happens if you try to access the COPIED array without passing it.
# Accessing the array without passing it
doo() # the function can access the original array
print(myArray, id(myArray)) # print the original array, CHANGE STAYS
Cool.
s = []
def fillItA():
s[0] = 1
print(s)
def fillItB(a):
a[0] = 99
print(a)
############################
ss = [0]
def fillItC():
ss[0] = 1
print(ss)
def fillItD(a):
a[0] = 99
print(a)
############################
# when the list starts with no values
# uncomment one function at a time
#print(s) # keep this uncommented as you test the next 2 lines
#fillItA() # attempt to access empty s[] directly
#fillItB(s) # attempt to access empty s[] by passing it to the function
############################
# when the list starts with a value
# uncomment one function at a time
#print(ss) # keep this uncommented as you test the next 2 lines
#fillItC() # attempt to access ss[] directly. Note ss has a starting value
#fillItD(ss) # attempt to access ss[] by passing it to the function. Note ss has a starting value
Very Cool.
Tuples are a data structures that cannot be changed. Think of tuples like a permanent (immutable) list. Tuples are covered in the Python Documentation.
myList = [22, 4, 99] #build a list, elements can change
myTuple = (22, 4, 99) #build a tuple, elements CANNOT change
#I want to get input, and hold it in a list.
myList[0] = input('Change the value in the first element of the list: ')
print(myList) #see, it changed
#YOU CANNOT CHANGE A TUPLE: myTuple[0]=input('change a value: ') #CRASH!!
myNewTuple = tuple(myList) #CAST myList INTO a TUPLE
print(myNewTuple) #print the Tuple
someList = list(myNewTuple) #CAST myNewTuple INTO a LIST
print(someList) #print the LIST
Dictionaries are a data structure that stores values in pairs. Think of dictionaries as data with a relationship, like a country and its capital ... or a friend and their phone number. Dictionaries are covered in the Python Documentation.
contacts = {'bob':6471234567, 'sally':6477778888} #build a dictionary
#you can also build dictionaries using the dict() constructor. Check out the API for details
print(contacts) #print the dictionary, notice the unfriendly output
#use a for loop to make the output more readable
for name,tel in contacts.items(): #use the item() to access the key and value
print(name, tel)
contacts['jojo'] = 6475556666 #add a key and value to the dictionary
print(contacts)
aListofKeysOnly = list(contacts.keys()) #Just the keys, put in a list
print(aListofKeysOnly)
aListofValuesOnly = list(contacts.values()) #Just the values, put in a list
print(aListofValuesOnly)
del contacts['bob'] #where did bob go?
print(contacts)
There's more functionality within the short tutorial in the documentation. Check it out.