Python Lesson 9: Nested Lists and Tuples

Advertisements

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 8: Sets & Dictionaries

Advertisements

Hello everybody,

Michael here, and today’s post will cover sets and dictionaries in Python. In the last post I covered lists and tuples, which are two of the four major types of collections in Python (sets and dictionaries being the other two).

First off, let’s discuss sets. Sets are collections of items that are unordered and unindexed:

Let’s take an example of a set:

This is a set of random years. Sets are written in curly brackets (on the other hand, tuples are written in round brackets and lists are written in square brackets).

Now, let’s see how we can access an item in a set:

Screen Shot 2020-03-02 at 9.19.56 PM

So how can we access items in a set? Well, we can’t. After all, since sets are unindexed, you can’t call a certain index like you can with lists and tuples.

However, you can loop through all the items in a set with a for loop:

You can also check to see if a certain item is present in a set:

Ok, so checking to see if an item is in a set isn’t the same process as it would be for a tuple or list. It’s also a lot simpler (just taking one line) and doesn’t print out a message. Rather, True would be printed if the specific item is in the set, and False would be printed if the specific item isn’t in the set.

Now what should we do if we want to add an item to a set? Granted, you can’t change items in a set, but you can certainly add and remove items in a set. Here’s how you would add items to a set:

As you can see, there are two possible methods for adding items to a set-add and update. The only difference between these two methods is that you would use add if you only wanted to add one item and update if you wanted to add several items.

You also likely noticed that the parameter I used for add is an int, but the parameters I used for update are String. This is because the update method won’t work with integers, so I had to make the years String. One thing I didn’t realize would happen when I did this was that all of the individual digits from each String were going to be printed as separate elements (and that no two digits would be repeated). Hey, even someone as programming-savvy as myself learns new coding caveats each time.

Now let’s try and remove an item from the set:

Just as there are two methods for adding an item to a set, there are also two methods for removing items from a set-remove and discard. Unlike the two methods for adding items, these methods are interchangeable. The only difference between these two methods is that remove will raise an error if the item you’re trying to remove doesn’t exist-discard will not.

You can also use the pop method to remove an item from a set:

Keep in mind that even though pop removes the last item from the set, sets are unordered, so you’re not going to know which item is going to be removed until you print out the list after using pop.

If you wanted to clear a set, use clear name_of_set. If you wanted to delete an entire set, use del name_of_set.

Now, let’s take a look at joining sets. Here’s an example as to how to do that:

First of all, I made a new set yearset2 (I needed to make a new set in order to have something to join my current set to). I then used the union method to join the two sets together and stored the new joined set as a new variable called years, which I then printed out.

Another way I could’ve joined yearset and yearset2 was with the update method; I could’ve written yearset.update(yearset2)and that would’ve accomplished the same thing as using the union method.

  • The union and update methods both omit duplicates.

Last but not least, let’s check the length of the set (using yearset):

Now that I’ve covered everything about sets, let me move on to dictionaries. Dictionaries are collections of items that are unordered, changeable, and indexed. They are written with curly brackets and have keys and values. Here’s an example of a dictionary:

The keys (country, state, and city) are to the left of the colon while the values (United States, Tennessee, and Nashville) are to the right of the colon. The keys don’t need to be String, but if you want to use words as keys, then you must put them in double quotes.

  • It might help to think of a Python dictionary like an actual dictionary, where the keys are the words and the values are the definitions.

So, how can we access the items of a dictionary? (It’s not the same way you would access the items of a set, list, or tuple):

 

These are two examples of incorrect ways to access elements in dictionaries. The first example is incorrect because Tennessee is a value, not a key, and you can’t try to access elements in a dictionary by directly calling values. The second example is incorrect because you can’t call an index in a dictionary like you can with a list, set, or tuple (though I might add that the second example would be correct if you had 2 as a key).

Here’s the correct way to access items in dictionaries:

The only way to access items in dictionaries is by calling the key. Remember to put the name of the key in full quotes if the key is a String.

  • I could’ve also used the get method, typed dict1.get(country) into Jupyter notebook, and gotten the same result.

So, now let’s change the values of this dictionary:

In this example, I changed city to Miami Springs and state to Florida​, then printed out the resulting dictionary. To change an element in a dictionary, use the syntax dictionary name[key name] = new value for that key.

You can also loop through the elements of a dictionary, just as you can loop through the elements of a list, set, or tuple. Here’s how to loop through the elements of a dictionary:

So while this loop did iterate through the elements of this dictionary, it only returned the keys of the dictionary, not the values. If you want to return the values of this dictionary, here are two ways to so:

In the first example, you would use the syntax print(dictionary name[x*]) to print out all of the values of the dictionary. In the second example, you would use the values method and the syntax dictionary name.values() to print out the values of the dictionary.

  • *Use whatever letter you have after for in place of x

If you want to loop through both the keys and values of a dictionary (and print them both), use the items method:

Now let’s see how we can check to see if an item is in a dictionary:

In this example, I am checking to see if the key state is in dict1 and if it is, I will print out the message State is in this dictionary (this is exactly what happened here).

Interestingly, this same approach doesn’t work when you want to check if a certain value is in a dictionary (recall that Tennessee was one of the original values in the dictionary). Not quite sure why this is the case:

Now, how would we add a new element to our dictionary? Here’s how:

Since dictionaries have two elements-a key and a value-you need to create a new key as well as a new value if you want to add an element to the dictionary.

Now, let’s see what we should do if we want to remove an element from the dictionary:

Just as with lists, sets, and tuples, you can use the pop method on a dictionary to remove an item.

However, there is also a method called popitem, which will remove the last key-value pair in the dictionary (unless you’re using a Python version before 3.7, in which case a random item will be removed instead):

If you wanted to remove more than just a single key-value pair, the del and clear methods are just what you would want. Del would delete a dictionary completely, while clear would simply empty the dictionary without deleting it.

  • An important caveat to note is that you could also use del to remove a key-value pair in a dictionary (along with being able to delete a dictionary completely).

 

Now, what should we do if we want to make a copy of our dictionary (keep in mind I added back the elements I had previously removed):

First of all, simply writing dict2 = dict1 wouldn’t work because dict2 would simply be a reference to dict1, rather than a copy of dict1. In order to create a copy of a dictionary, use the copy method.

You could also use the dict method with the syntax name of new dictionary = dict(name of current dictionary) to copy your current dictionary.

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

You would use the len method to check the length of a dictionary, just as you would when you want to check the length of a tuple, list, or set. But why is len 4 and not 8? This is because key-value pairs are counted as one item, and since there are 4 key-value pairs, len is 4.

Thanks for reading,

Michael