Python Lesson 7: Lists & Tuples

Advertisements

Hello everybody,

It’s Michael, and this post will be the first in a new series of Python posts. Today’s Python post will cover lists and tuples.

List and tuples are two of the four major collection types in Python (sets and dictionaries being the other two), but what are the differences between them?:

  • Lists are ordered and changeable; duplicates are allowed
  • Tuples are ordered but unchangeable; duplicates are also allowed
  • Dictionaries are unordered but changeable and indexed; no duplicates here
  • Sets are unordered and unindexed; no duplicates here

Still stumped about lists, tuples, dictionaries, and sets? Don’t worry, I’ll explain lists and tuples in today’s posts (I’ll explain dictionaries and sets in the next post).

I’ll start with lists. Here is a very simple example:

This list contains the names of three states. Notice anything else familiar?

If you were thinking of the square brackets, you are correct. See, arrays in Python (and Java for that matter) also use square brackets. Also, by the way lists are structured, you might’ve thought they were arrays (and Python lists and arrays are very easy to mix up with each other).

So how do lists and arrays differ from each other? Here are three ways:

  • Arrays have to be declared while lists don’t (recall that, more often than not, you won’t need to declare variable types in Python) since lists are automatically recognized as such by Python.
  • While lists work fine storing many different data types, if you need to do arithmetic functions on a series of elements, you’re better off using arrays.
  • Arrays store data more compactly and efficiently than lists, so if you’ve got lots of elements (like tens of thousands of elements), you’re betting off storing them in an array.

How do you extract elements from a list? It’s pretty much the same way you would with an array:

Screen Shot 2020-02-08 at 6.31.47 PM

As you can see from this list, you would extract an element in a list by writing list name[list element]. You can use either a print or return statement to print the element you are looking for, but don’t use both.

  • Remember that, like with arrays in Java, lists start at element 0, so when I picked element 2 from the list, I was really choosing the third item in the list, not the second.

The example I just showed you is a really basic example as to what a list can do. You can also select a range (or ranges) of elements in lists, just as you can with arrays in Java. Here’s an example:

In this example, I selected elements 1-3 from the stores list. But how come only two elements were printed? When you are selecting elements for a range, the last element is excluded. In other words, the lower bound listed in the range (1 in this example) will be included but the upper bound for the range (3 in this example) won’t be included. The range will only display elements from the lower bound to the upper bound-1 (2 in this example).

But wait, there’s another way to select elements from a list in Python. It’s called negative indexing and here are two examples of that (the first showing an individual element selection and the second showing a range:

Negative indexing is essentially the reverse of regular indexing, as the first index is the last item in the list and the last index is the first item in the list. Also keep in mind that the last item in the list corresponds to index -1 because after all, there is no -0.

When choosing ranges in negative indexing, the same upper bound/lower bound logic that applies to regular indexing also applies here. Even though you have an upper bound and lower bound, the lower bound will be displayed but the upper bound won’t be displayed. Rather, the element BEFORE the element in the upper bound will be the last element displayed.

One more thing regarding choosing ranges in lists that I wanted to mention is that, whether using negative indexing or regular indexing, you don’t need both an upper or lower bound (but you can’t have neither, because that’s not a range). Here are two examples (the first using regular indexing and the second using negative indexing):

In the first print statement in the regular indexing example, everything from index 2 (3rd item in the list) onwards is printed. In the second print statement, everything up until BUT NOT INCLUDING index 3 (4th element) is printed.

In the first print statement in the negative indexing example, everything beyond BUT NOT INCLUDING index -2 (5th item in the list) is printed. In the second print statement, everything from index -4 (3rd item in the list) onwards is printed.

OK, now that I’ve discussed selecting items from lists, let’s now talk about modifying lists.

The first thing I want to discuss is changing elements in lists. Here’s an example:

In this list, I changed index 4 (the 5th item in the list) to Captain Marvel then printed out the new list with the changed index. If you want to change an element in a list, here is the syntax for doing so:

  • List name [list index you want to change] = new element for that index

Now let’s talk about adding items to a list. In Python, there are two methods for accomplishing this-append and insert. Both methods add items to list, but append will only add items to the end of a list while insert will add items at any position in the list (so long as you specify the position where you would like to add an item). Here’s an example of each method in action (along with the new list after each method is executed):

In this example, I appended Thor The Dark World to the list as well as added Spider-Man Homecoming to the list at index 2 (which is the 3rd element).

Now, what should we do if we want to remove items from a list? There are three possible methods for doing so-remove, pop, and del. Remove will remove a specified item from the list, pop will removed a specific index (which corresponds to a specific item) from the list-or the last index if an index isn’t specified, and del will also remove a specific index.

  • Keep in mind that when using del, you must specify an index, but you don’t have to specify an index if you’re using pop.

Now, here’s an example of the remove, pop, and del methods in action, along with the resulting list (keep in mind that this list is building from the list in the previous example):

In this list, I removed the element Captain Marvel, popped off the last element of the list (since I didn’t specify an element to pop off, pop will automatically remove the last element of the list), and deleted index 1 (the 2nd element) of the list.

The last thing I want to discuss about lists is how you can see whether or not an element is in a list. Here’s an example of this:

In this example, I am checking to see whether or not Avengers Infinity War is in the list MARVEL (the list I made from concatenating MCU and nonMCU). Depending on whether Avengers Infinity War is in the list MARVEL, one of two messages will appear-either Infinity War is in this list or Infinity War isnt in this list. Since the aforementioned element wasn’t in the list MARVEL, the message Infinity War isnt in this list is printed.

  • Jupyter notebook indents the bodies of if-else statements, loops, and functions (which I’ll discuss in a future lesson). Spyder doesn’t do this.

Last but not least, let’s see how we can find the length of a list:

To find the length of a list, simply write len (name of list). That’s it.

Now that I’ve discussed everything I wanted to discuss about lists, let me move on to tuples.

Tuples are similar to lists since both are ordered collections of items. However, tuples are written with round, not square, brackets, and unlike lists, they are unchangeable, which means you can’t modify the tuple in any way.

One great example of tuples is the coordinate plane (the one you were likely first introduced to in school). The coordinate plane is full of tuples, such as (3,2), (2,7), and (-1 5), just to name a few.

Now, let’s first see how we can access tuple items:

Notice anything familiar? If you do, it’s because you would access a tuple item the same way you would a list item. However, you must write print before the part where you access the tuple item, since tuples aren’t callable on their own (and I got an error message when I tried to execute the statement vegetables[1])

Now, how would we use negative indexing in a tuple? Let’s take a look:

As it turns out, negative indexing with a tuple is the same as negative indexing with a list. Just remember to write print before the part where you access the tuple item.

Now, how would we select a range of items in a tuple (using both regular and negative indexing):

Well what do you know? Selecting ranges of items in tuples is the same as selecting ranges of items in lists. Even the same inclusion/exclusion rules apply-by that I mean the index corresponding to the lower bound (1 and -3 in this example) will be included in the output while the index corresponding to the upper bound (4 and -1 in this example) will be excluded.

Now, how would be change an item in a tuple? Let’s find out:

Yeah, you can’t change items in a tuple-this was basically a trick question (I did mention that tuples were unchangeable at the beginning of this post).

But, there is a workaround for this. Here’s how that would work:

I first converted the vegetables tuple into a list, which is referred to as vegetables2. I then changed index 2 in vegetables2 to zucchini, converted vegetables2 back into the original vegetables tuple, and printed the new vegetables tuple.

So if you ever need to do something like this, here’s how to change an item in a tuple:

  • Turn tuple into list
  • Change element in list
  • Turn list back into tuple

Now, how would we add or remove items from a tuple? Let’s find out:

  • Keep in mind that I’m trying to add an item on the first line but trying to remove an item on the second line.

OK, I’ll admit this was a total trick question. Tuples are unchangeable, meaning that you can’t add or remove elements from tuples.

You can, however, delete a tuple completely using the syntax del name_of_tuple.

Now, let’s see how we can join-or concatenate-two tuples together:

In this example, I made a new tuple fruits which I joined with the vegetables tuple to make the fruitsandvegetables tuple, which I then printed out.

Next up-let’s see how we can check whether or not an item is in a tuple:

The process for checking whether an item is in a tuple is identical to the process for checking whether an item is in a list (though an else statement isn’t necessary).

Let’s next look at iterating through a tuple with a for loop:

The process for iterating through a tuple with a for loop is the same as the iteration process with a for loop for a list.

Last but not least, let’s see how we check the length of our tuple:

Simply using the len method (along with the name of the tuple) will allow you to check the length of the tuple.

Thanks for reading,

Michael