Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Python Basics Exercises: Lists and Tuples (Summary)

In this course, you’ve reviewed what you learned in Python Basics: Lists and Tuples. You’ve used Python lists and tuples to store collections of objects, and you’ve gained a stronger understanding of the best use cases for each data type.

In this video course, you’ve practiced:

  • Defining and manipulating lists and tuples in Python
  • Leveraging the unique qualities of lists and tuples
  • Determining when you should use lists vs tuples

Now you have an even stronger grasp of Python lists and tuples, and you’re ready to effectively incorporate them into your own programming projects.

For more on lists and tuples, check out:

You can learn more about various operations with the following resources:

This video course is part of the Python Basics series, which accompanies Python Basics: A Practical Introduction to Python 3. You can also check out the other Python Basics courses.

Download

Sample Code (.zip)

3.7 KB
Download

Course Slides (.pdf)

5.6 MB

00:00 And that’s it. Congratulations for making it to the end of this Python Basics Exercises course about tuples and lists. I have a couple of friends here from earlier to celebrate together.

00:11 Looks like everyone’s really happy about finishing the course. Congratulations again.

00:17 So as a quick recap, in this course you practiced using tuples and lists and also associated concepts with this data structure, such as how to use indexes on tuples and lists, how to slice them, how to use tuple unpacking and how to create list comprehensions.

00:33 And then towards the end, you’ve also looked at a potential issue that comes from the mutability of lists. And yeah, along the way you’ve also practiced other programming concepts such as conditional logic and loops.

00:45 On top of these programming topics, you also practiced additional meta topics that are super helpful when you’re building projects, programs, or just working with code: use code comments to help you get organized, potentially break exercises into smaller tasks, try different approaches to solve a task, and then maybe discard some when you figure out which is the best.

01:08 Refactor your code, definitely at the end, but probably somewhere in between. You can always refactor on the way and make your code better and more consistent and easier to reason about.

01:19 You’ve also used descriptive variable names and tested repeatedly to see whether the code actually does what you expect it to do. So all of these tips are helpful in any coding scenario, not just when you’re working with lists and tuples, obviously.

01:33 Okay. Here are a couple of additional resources if you want to continue your learning journey about lists and tuples. So we have lists and tuples tutorial and course that goes over both data types.

01:44 And then there’s dedicated tutorials for each of them that each go very deep. That’s why they’re called the deep dive. So if you want to learn more about any of the two or both, then check out these resources,

01:57 and we have more. So take a look in the course catalogs, search for list or tuple, and you’ll come up with a couple of other resources such as the three that definitely stood out here.

02:09 And with that, I want to say congratulations and thanks for joining. I hope you had a fun time practicing to work with tuples and lists. I wish you all the best. See you around Real Python.

Avatar image for alvesmig

alvesmig on Feb. 8, 2024

Hello, my solution is almost the same as yours.

I have a question: Which one is better, yours which is written completely in a function or mine which only uses a little function to get the article?

Best regards Miguel

Here is my solution:

import random

nouns = [...]
verbs = [...]
adjectives = [...]
prepositions = [...]
adverbs = [...]

def get_article(word):
    first_letter = word[0].lower()
    if first_letter in {"a", "e", "i", "o", "u"}:
        return "An"
    return "A"


noun1, noun2, noun3 = random.sample(nouns, k=3)
verb1, verb2, verb3 = random.sample(verbs, k=3)
adj1, adj2, adj3 = random.sample(adjectives, k=3)
prep1, prep2 = random.sample(prepositions, k=2)
adverb = random.choice(adverbs)


poem = (
    f"\n\n{get_article(adj1)} {adj1} {noun1}\n\n"
    f"{get_article(adj1)} {adj1} {noun1} {verb1} {prep1} the {adj2} {noun2}\n"
    f"{adverb}, the {noun1} {verb2}\n"
    f"the {noun2} {verb3} {prep2} the {adj3} {noun3}"
)        


print(poem)
Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on Feb. 9, 2024

@alvesmig At the end of the day, what really matters is that your code works as expected and that it gives you the correct result. Once you’ve tested the code for correctness, you may start thinking of ways to make it better, which is a highly subjective matter. Do you intend to make it run faster, use fewer dependencies, look more concise, or be easier to maintain?

Knowing where to set the boundaries between your functions is a skill that comes through practice. After some time, it starts to feel natural when to define a function and which code to put into it.

As a rule of thumb, defining small functions with clear responsibilities is considered a good practice. That way, you can reuse your functions in different situations and even combine them with others in flexible ways. In contrast, keeping most of your code within a single function or the global scope can make it more difficult to test, understand, and reuse.

Avatar image for alvesmig

alvesmig on Feb. 9, 2024

Thank you!

Avatar image for johnlukow

johnlukow on Feb. 19, 2024

I have really enjoyed the site so far. I went beyond the poem and did a MadLib. I created several lists and a general purpose function to return a random of each. Great lessons. I feel like I really understand list. I am not sure how/if I will use Tupel, but I will keep an eye out.

def madlib(type):
    element = random.choice(type)
    return element

# MadLib version

story = ( 
    f"This weekend I am going camping with {madlib(name)}. I packed my lantern, sleeping bag, and\n"
    f"{madlib(noun)}. I am so {madlib(adjective)} to {madlib(verb)} in a tent. I am {madlib(adjective)} we\n"
    f"might see a {madlib(animal)}, they are kind of dangerous. We are going to hike, fish, and {madlib(verb)}.\n"
    f"I have heard that the {madlib(color)} lake is great for {madlib(verb)}. Then we will\n"
    f"{madlib(adverb)} hike through the forest for {madlib(number)} {madlib(time)}. If I see a\n"
    f"{madlib(color)} {madlib(animal)} while hiking, I am going to bring it home as a pet! At night we will tell\n"
    f"{madlib(number)} {madlib(silly_word)} stories and roast {madlib(noun)} around the campfire!!"
    )

print(story)
Avatar image for Martin Breuss

Martin Breuss RP Team on Feb. 19, 2024

@johnlukow great MadLib script :D Kudos on taking the exercise and running with it 👏

Avatar image for johnlukow

johnlukow on Feb. 19, 2024

@martin breuss: I did have one question. If I were to use sample instead of choice in my general function. Would sample “remember” the previous items chosen, or does it only work in the same call? I made sure my lists were long to avoid the duplication discussed in the lesson, but I would further optimize my madlib() function if this worked.

Avatar image for Martin Breuss

Martin Breuss RP Team on Feb. 20, 2024

@johnlukow each call to random.sample() is a separate call and there’s no shared state between these function calls:

>>> from random import sample
>>> words = ["Hello", "World!", "I", "am", "a", "person!"]
>>> sample(words, k=2)
['am', 'person!']
>>> sample(words, k=2)
['World!', 'am']

So, while using random.sample() with a k value makes sure that you won’t get the same word twice during one call, it doesn’t do anything like that between multiple calls.

If you want to make sure that your MadLib doesn’t use words from your lists twice, then you’d have to set it up differently—for example with the approach that I show in the lesson where you pick them all out at once and then interpolate each word into the final string.

Avatar image for rwelk

rwelk on March 3, 2024

A lot of fun Thanks

Avatar image for ajackson54

ajackson54 on July 6, 2024

The Poem Generator was fantastic! I’m going to spend a few hours experimenting with this.

Avatar image for ajackson54

ajackson54 on July 7, 2024

I’ve made a simpler version of your code to practise and experiment with. Here is my code for a story generator.

import random

word1 = ['walked', 'ran', 'went', 'flew']
word2 = ['store','park', 'farm', 'city']
word3 = ['brother','sister', 'mother','friend']
word4 = ['ate','shopped','stayed','talked']

words = [word1, word2, word3, word4]

def make_story(words):

    word1 = random.sample(words[0], k = 4)
    word2 = random.sample(words[1], k = 4)
    word3 = random.sample(words[2], k = 4)
    word4 = random.sample(words[3], k = 4)
    story = (f" I {word1[0]} to the {word2[0]} with my {word3[0]} and {word4[0]} until we came home.")
    return story

print(make_story(words))

I’ll use this for an outline and enhance it with articles and maybe paragraphs. I might even experiment with different random functions.

I’m having problems with the formatting again. Why does this happen?

Avatar image for Martin Breuss

Martin Breuss RP Team on July 8, 2024

@ajackson54 hi, great that you’re experimenting more with the code :)

For the formatting, like I mentioned in another reply, you’ll need to wrap your code in triple backticks (and optionally add a syntax highlighter) for it to render as fenced code blocks.

That’s just how formatting code works in Markdown. If you don’t use the triple-backticks, then it’ll interpret the indentation as a code block, and that messes up the formatting because indentation has meaning in Python. Try it out in an online Markdown editor!

Become a Member to join the conversation.