Python Lesson 9: Nested Lists and Tuples

Hello everybody,

It’s Michael, and today’s post will be about nesting. This post will involve lists, tuples, sets, and dictionaries, but it won’t necessarily be a continuation of my last two Python posts. In this post, I’ll be demonstrating nested and tuples (with the next post covering nested sets and dictionaries).

First I will demonstrate a nested list (think of this as a list-within-a-list):

fruitsandveggies = [‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’,], ‘apples’
, ‘strawberries’]

And here’s some sample output (based on me choosing a specific element from the nested list):

print(fruitsandveggies[2][1])

celery

In this example, I have the nested list fruitsandveggies and have selected element [2][1] from the list. However, you’re probably wondering what element I’m referring to when I say [2][1]. In this list, [2] refers to the outermost list while [1] refers to the innermost list. So when I want to pick element [2][1] from the fruitsandveggies list, I’m saying that I want to pick index 2 (the 3rd item) from the outermost list and index 1 (the 2nd item) from the innermost list (the corresponding element is celery).

So whenever you see something like fruitsandveggies[2][1], remember that the first index ([2] in this case) represents the outermost list and any subsequent indexes represent lists that are further inward. In this example, [1] would represent a list that is further inward. Had I included more nested lists, any subsequent indexes would’ve represented lists that were further inward. The last index listed would represent the innermost list.

So remember that when you see something like list name[a][b][c][d][e], remember that the first index listed (represented by [a]) would represent the main list. Any subsequent indexes (represented by [b], [c], and [d])  represent lists that are further inward, while the last index (represented by [e])  represents the innermost list.

  • Helpful tip-when you are selecting an element from a nested list, remember to choose an index with a nested list! For instance, a statement like print(fruitsandveggies[3][1])​  wouldn’t have worked because index 3 (the 4th item in the outermost list) doesn’t contain a nested list.

You can also do many of the same things with nested lists that you can with normal lists, such as:

…negative indexing

fruitsandveggies = [‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’
, ‘strawberries’]

print(fruitsandveggies[-3][-1])

zucchini

Remember that the negative indexing rules that apply for regular lists also apply for nested lists (e.g. first index in negative indexing is -1, not 0)

…adding items to the list (using the same methods you would use for regular lists)

fruitsandveggies.append(‘grapefruit’)
fruitsandveggies.insert(2, ‘squash’)

print(fruitsandveggies)

[‘bananas’, ‘oranges’, ‘squash’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’, ‘grapefruit’]

In this example, I used append to add the item grapefruit to the list and insert to add squash to the list.

When using these methods with nested lists, keep in mind that the appended item will be added to the outermost list, not any nested lists. Also keep in mind that when you use the insert method in a nested list, the index you want to place the element in corresponds to the outermost list, not any nested lists. In this example, I wanted to insert the element squash at index 2; this means that squash would be inserted at index 2 OF THE OUTERMOST LIST.

…removing items from the list (using the same methods that work for normal lists):

fruitsandveggies.pop()
del fruitsandveggies[2][1]

print(fruitsandveggies)

[‘bananas’, ‘oranges’, [‘peppers’, ‘zucchini’], ‘apples’]

In this example, I used the pop and del methods to remove items from the list fruitsandveggies. Pop removed the last item from this list; however, it might have removed a different element had I specified an element to remove. Del removed the item from this last that was located at the index I specified- [2][1] (meaning that the item at index 1 of the nested list was removed).

…finding the length of a list:

fruitsandveggies = [‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’
, ‘strawberries’]

print(len(fruitsandveggies[1]))
print(len(fruitsandveggies[2]))

7
3

Finding the length of a nested list is essentially the same as finding the length of a regular list (you would also use the len method), but include an index after the list name. The index will let Python know the list whose length you wish to find. For instance, if you use the index [1], you will get the length of the entire list (which in this case is 7). However, if you were to use the index [2], you would get the length of the nested list (which in this case is 3) . If I had more nested lists in this example,  I would use indexes such as [3], [4], [5], and so on, depending on how far inward the lists were located.

Last but not least, let’s see how we can iterate through the elements of a nested list:

for list in fruitsandveggies:
for i in list:
print(fruitsandveggies)

[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]

In this example, I iterated through this nested list with a nested for loop. One thing I didn’t realize when I created this loop was that the list was going to be printed 21 times (I’m guessing it’s 21 times because there are 7 elements in the main list while there are three elements in the nested list, so 7 * 3 = 21).

Next, I will demonstrate nested tuples. But first, let me show you how to create a nested tuple, as the process isn’t as simple as the one for creating a nested list:

tuple1 = (1, 3, 5, 7, 9)
tuple2 = (0, 2, 4, 6, 8)
tuple3 = tuple1, tuple2
print(tuple3)

((1, 3, 5, 7, 9), (0, 2, 4, 6, 8))

See, with a nested list, all you would need to do is write a list-within-a-list (or several lists-within-lists). On the other hand, with a nested tuple, you would actually need to create a new tuple that concatenates your other tuples, as I did in the above example (and yes, you can use a comma to concatenate your tuples. This is not Java).

Now, let’s say we wanted to access an item in our nested tuple. How do we do that?:

print(tuple3[1][1])

2

The process for accessing an item in a nested tuple is the same as it is for accessing an item in a nested list-use multiple indexes to get the element you want. However, the way indexes are counted in nested tuples differs from the index counting in nested lists, as individual tuples-within-the-tuple are counted as individual indexes. For instance, in tuple3, the first tuple (tuple1) counts as index 0 while the second tuple (tuple2) counts as index 1.

But what if I had only used a single index? Let’s see what would happen:

print(tuple3[1])

(0, 2, 4, 6, 8)

In this example, I used a single index-[1]-and got the entire second tuple as a result.

  • Remember that if you want to get a single tuple element, use multiple indexes. If you want to get a whole tuple, use a single index.

Negative indexing also works with nested tuples. Here’s an example (using both single and multiple indexes):

print(tuple3[-1])

(0, 2, 4, 6, 8)

print(tuple3[-1][-3])

4

How would we iterate through a nested tuple? We would basically use the same process we use to iterate through regular tuples:

for i in tuple3:
print(i)

(1, 3, 5, 7, 9)
(0, 2, 4, 6, 8)

Interestingly, the tuples printed out separately-by this I mean the tuples-within-the-tuple are displayed on separate lines rather than on the same line separated by a comma.

Now, how would we find the length of a nested tuple? Let’s find out:

print(len(tuple3))

2

How did I get 2 instead of 10? In this example, Python counted each individual tuple-tuple1 and tuple2-inside of my large tuple-tuple3-as an individual element. Since there are two tuples-within-the-tuple, len returned 2.

You may have noticed that I didn’t mention anything about adding or removing elements from nested tuples. This is because the methods that work for adding and removing items from regular tuples won’t work for nested tuples.

Thanks for reading,

Michael

 

Python Lesson 7: Lists & Tuples

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:

Screen Shot 2020-02-08 at 2.37.39 PM

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:

Screen Shot 2020-02-08 at 6.46.59 PM

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:

Screen Shot 2020-02-08 at 7.09.15 PM

Screen Shot 2020-02-08 at 7.12.54 PM

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):

Screen Shot 2020-02-08 at 7.55.11 PM

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:

Screen Shot 2020-02-12 at 9.40.46 PM

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):

Screen Shot 2020-02-12 at 10.26.06 PM

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):

Screen Shot 2020-02-12 at 10.41.03 PM

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:

Screen Shot 2020-02-15 at 2.43.35 PM

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:

Screen Shot 2020-02-23 at 10.07.17 PM

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:

Screen Shot 2020-02-18 at 9.25.16 PM

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:

Screen Shot 2020-02-18 at 9.33.33 PM

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):

Screen Shot 2020-02-18 at 9.39.37 PM

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:

Screen Shot 2020-02-18 at 9.47.31 PM

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:

Screen Shot 2020-02-18 at 9.53.09 PM

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.

Screen Shot 2020-02-23 at 2.26.49 PM

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:

Screen Shot 2020-02-23 at 2.38.11 PM

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:

Screen Shot 2020-02-23 at 2.46.47 PM

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:

Screen Shot 2020-02-23 at 2.58.25 PM

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:

Screen Shot 2020-02-23 at 3.02.41 PM

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