Working with Arrays


The course is part of this learning path

Working with Arrays

In this first course, we introduce the Python Language, the declaration model, and how variables and functions are used in python.

Our learning objectives for this course are to introduce the python language and to be able to recognize and explain the core concepts of the Python language.


Hello, and welcome back. Let's do a quick overview of array types. In this lecture, our learning objectives are to learn how to use single and multi-dimensional lists and tuples, indexing and slicing sequential types, looping over sequences, tracking indices with enumerate , using range to get numeric lists and transforming lists. Python provides many data types for working with multiple values. These hold values in a sequence such that they can be retrieved by a numerical index, a string, or Str, is an array of characters. A bytes object is an array of bytes. An array type may be indexed in the same way, retrieving a single item or a slice which has multiple values of a sequence. Array types have some features in common with other container types, such as dictionaries and sets. All array types support iteration over their elements with a for loop. To get ourselves familiar with the concept, so I've created three arrays, one fruit, one name, one knight. And I've given each some variables. Okay, so now let's work with these. I'm gonna save this first, and call it an array just for now. And look at that, great. So our compiler's told us that we have an error which if you can spot it, it's that full stop after the pear, that should be a comma. So let's just fix that. Okay, we'll try and run that again. Yeah, alright, so it's run and compiled without throwing any exceptions, but we have not printed anything out. So let's print out our variables, chosen variables from this array. So we'll go print fruits first and let's take fruit number, we'll take the kiwi, let's take fruit number three. Now remember, we count from zero, so apple is actually zero. Second, let's print out from the name array. Let's just print out one letter from that. So we'll print name and we'll take the first letter A, which is gonna be zero. All right, close it out. And we'll print out one variable from our knight array. Let's take number two from that, which is New Zealand. We'll take number one, which is Andrew. Okay, all right. Now there's an error in here, see if you spotted it yet? We'll run this and it should throw an exception for us. Yes, where is it? That's right bracket at the end. Okay, okay, and it's throwing us the values that we wanted. In the first slide, we print all fruits with variable number three, and then second, we print the name. And third, we print the first of our knight array. 

A list is one of the fundamental Python data types. Lists are used to store multiple values. The values may be similar, all numbers, all usernames, and so forth. Or they may also be completely different. Due to the dynamic nature of Python, a list may hold values of any type, including other lists. We create a list with a pair of square brackets. A list can be initialized with a comma separated list of values. We simplify things by using the split command. Then let's print list1, list2 and list3 and list4. We'll take items from each of those and we'll print the first item from list2 and the fourth item from list4. Now I've just put an error in there, you should be able to see the error. Okay, let's also print out the last element of list4. Right, using the minus one count. Okay, now, when we run this, we should see an error yeah, that we do, list index out of range. So the problem there is that our variable declaration should be two, not one. If we run that, again, that returns the variables we want. Python has a second array type, the tuple. It is something like a list but is immutable. That is, you cannot change values in a tuple after it has been created. A tuple in Python is used for records or struts, which are collections of related items. You do not typically iterate over a tuple, it is more likely that you access elements individually or unpack the tuple into variables. Tuples are especially appropriate for functions that need to return multiple values. They can also be good for passing function arguments with multiple values. While both tuples and lists can be used for any data, there are some conventions to consider. Use a list when you have a common collection of similar objects. Use a tuple when you have a collection of related but dissimilar objects. In a tuple, the position of elements is important. In a list the position isn't important. So for example, you might have a list of dates where each date was contained in a month, day, year tuple. To specify a one element tuple, use a trailing comma. To specify an empty tuple, use empty parenthesis. To specify a one element tuple, use a trailing comma otherwise it will be interpreted as a single object. Indexing and slicing. Python is very flexible in selecting elements from a list. All selections are done by putting an index or a range of indices in square brackets after the list's name. To get a single element, specify the index, which remember is zero based, of the element in the square brackets. To get more than one element, use a slice, which specifies the beginning element, inclusive, and the ending element, which is exclusive. If you omit the starting index of a slice, it defaults to zero. If you omit the end element, it defaults to the length of the list. A negative offset is subtracted from the length of the list. So minus one is the last element of the list, and minus two is the next to the last element of a list and so forth. The general syntax for a slice is start, stop, step. 

So let's think about how we iterate through a sequence. For that we use the for loop, which works with lists, tuples, strings and any other iterable. The syntax for iterating through a sequence is, for var in iterable, statement, statement. So to iterate through values of a list, use the for statement. The variable takes on each value in the sequence and keeps the value of the last item when the loop is finished. To exit the loop early, use the break statement. To skip the remainder of an iteration and return to the top of the loop, use the continue statement. For loops can be used with any iterable object. Now the loop variable contains the last value it was set to in the loop, even after the loop is finished. So if the loop is in a function, the loop variable is local, otherwise, it is global. So in our example here, first we iterate over elements of the list. Second, we iterate over elements of a tuple. And third, we iterate over characters of a string. Okay, as usual, I've put an error in here to make sure that you're actually watching. Can you see what it is? Yeah, it's to do with this bracket here. So we need to put the right brackets around our tuple. We make those to an open and closed bracket, that should run now. Now we can also change the output we're creating here, and instead of having a space between our characters, we could put a dash or anything at all. With number items beginning with zero, we can use the enumerate function. This returns the enumerate object that provides a virtual list of tuples. 

So to get the index of each list item, we use the built in function, enumerate . It returns an enumerate object. We can use operators and keywords for sequences. The operators plus and ampersand, the keywords Del, Not in and In. So Del deletes an entire string list or tuple. It can also delete one element or a slice from a list. Del cannot remove elements of strings and tuples because they are immutable. In, returns True if the specified object is an element of the sequence. Not in, returns True, if a specified object is not an element of the sequence. Plus adds one sequence to another, star multiplies a sequence, i.e it makes a bigger sequence by repeating the original. Okay, as an example, let's use our colors and months tuples. So we'll enumerate through those and print out a few and then we'll try a few of the additional functions. So first, we'll test for membership in the list and then we'll concatenate the iterable using the comma as the delimiter. And then let's permanently remove element with index for. Then we can remove element by value. And then we'll add three lists together and combine all the elements and let's even multiply a list and that replicates the elements. Alright, I've also put a couple of little bugs in here, have you spotted them yet? Let's run our script and see what goes wrong. Okay, the first issue is that we have a syntax issue here in the print removed green line, so we need to add an additional comma. The next issue with the script is that we have used the True and False names in the wrong way. So we have to make sure that the syntax is correct. Okay, with that fixed, we can now see the right results as we predicted. Now, the range function provides virtual lists or virtual list of numbers. It's got slice-like parameters, and its syntax is range , range , range . So the range function returns a range object. And that provides a list of numbers when iterated over. The parameters to range are similar to the parameters for slicing. This can be useful to execute some code, a fixed number of times for example. Okay, so let's print out a range, we use a number of different range functions here. First, we'll start at one and stop at six. So we're gonna take a range of one through five, and second here, start at zero and stop at six. So zero through to five. Then we'll start at three, and stop at 12. So three through to 11. And then we'll start at five, stop at 30 and then step five, okay? So we're gonna go five through 25 by five. And then last, let's do a start at 10, stop at one and then step at minus one. So we'll go 10 through one by one. Okay, now I've put a little bug in here. Have you spotted it yet? What's the one thing that's not gonna work in here? Let's try and run the script. And it's quite a simple indent issue, all right? So always remember to indent your code properly. Let's take that out and save it and then run it again. And we should get a output here that we want. Yes, all right. There's a range one to six, three to 12, five there we are. Nice. Okay, so that's the range function.

About the Author
Learning Paths

Andrew is fanatical about helping business teams gain the maximum ROI possible from adopting, using, and optimizing Public Cloud Services. Having built  70+ Cloud Academy courses, Andrew has helped over 50,000 students master cloud computing by sharing the skills and experiences he gained during 20+  years leading digital teams in code and consulting. Before joining Cloud Academy, Andrew worked for AWS and for AWS technology partners Ooyala and Adobe.

Covered Topics