Tuples and Lists Practice: Python Basics Exercises
Key Takeaways
This video course covers Python basics exercises, focusing on tuples and lists, including tuple unpacking, indexing, slice notation, and list comprehensions, using tools like IDLE and Python.
Full Transcript
welcome to this real python exercises course where you'll practice working with toes and lists which are two of Python's data types that represent collections our exercises courses are all about training you'll train the process of writing code by solving carefully selected exercises you also train reading other people's code and communicating your thought process doing all that you'll practice the concepts that you've learned about in an Associated course or tutorial and help make them stick in the upcoming lessons I'll introduce you to tasks give you an opportunity to solve them yourself and then show you step by step how I solved each of them you'll go through three steps for each task you'll learn about the exercise you'll code your own solution and then you'll compare Your solution at the process that got you there to mine when I walk you through a task I'll explain what I do and also why I do it like that that'll give you a chance to compare not just our final Solutions but also how we got there ideally this can help you gain some insights on the process of getting getting from a task description to a working solution in code in this course you'll start with solving some review exercises in the first section of the course and then build towards a challenge your challenge in this course will be to build a poetry generator and you'll get to train using lists and tuples in a slightly bigger project okay so now the big question are you ready for this course the idea of this exercises course is that you should have watched the python Basics course on T and lists before starting this one if you went through that course then you're well equipped to solve the tasks that you're about to encounter the concepts that you should have heard about and will practice are of course tupal and lists you'll train different aspects of these data structures such as indexing slicing Tuple unpacking list comprehensions and mutability you'll also train other Concepts such as conditional logic and Loops but this won't be the focus of the exercises if you're already somewhat familiar with these Concepts and you want to fortify your knowledge with PR practical programming tasks then this course is exactly right for you before you get started there's another tiny bit of background for this course which is that I'll use idle the integrated development and learning environment that comes with python if you've gone through the python Basics courses then you're already familiar with the tool if not and you want to know more then you can check out these Associated courses that cover getting started with idle but you don't need to use is specifically any other repple session and code editor will do so if you're here to train outside of the Python Basics course then feel free to use whatever tool you like to solve the upcoming coding tasks and that's all to get you set up are you ready to do some Hands-On programming what about you Mouse fox looks like everyone's ready so let's get started with the first review exercise in the next lesson let's start with the first exercise find a location by creating a tuple literal named location that holds two floating Point numbers 6.51 and 3.39 and then also the strings Lagos and Nigeria and they should be in that order and then use index notation to display the string at index two in location and finally use one line of code to unpack the values in location into four variables and name them latitude longitude City and Country and then print each of them on a separate line that's the task you're going to need to create a tuple use indexing to access a value and then also practice Tuple unpacking give it a try and then move on to the next lesson where you can see me solve the exercise let's start by creating the location Tuple so remember you can create a tuple by using the parenthesis or you can actually leave off the parenthesis but you need comma separated values I always like to put the parenthesis because it makes it more are clear that I'm creating a tuple so here the first value was 6.51 floating Point number the second one 3.39 and then we have a string Lagos and then another string Nigeria you can see here that tuples can hold different types of values so here we have two floating Point numbers and then two strings location looks good and it's of type Tuple the next task was to access at index two and I can do that by typing the name of Tuple location then use the square brackets and then put in the integer for the index that I want to access so index 2 is going to be the name of the city Lagos the third task was to practice tupal unpacking and assign each of those values in the Tuple to one variable starting by a latitude longitude City and Country and I'll set that equal to location so this's location variable here points to the Tuple that contains the values and it has four values in it and I'm putting four variables on the left side of the assignment statement so then python can unpack the location Tuple and assign each value of the Tuple to one of the variables on the left side so 6.51 is going to go into latitude Etc let's look whether that works right away so latitude now points to 651 longitude to 3.39 City to Lagos and Country to Nigeria I'm doing this in the reple which is why I've omitted the calls to print but if you did this in a script in order to actually display it you'd have to wrap it into a print call same output otherwise cool that's the task on to your next exercise this one is about person X use the Tuple function and a string literal to create a tuple that you call my uncore name and it should contain the letters of your name check whether the character X is in that Tuple and do that using the in keyword then create a new Tuple that contains all but the first letter in my name using slice notation so here you're practicing to create tupal using the Tuple function then using membership checking for an element inside of a tuple and for the third Point you'll have to create a copy of the Tuple because they're not mutable so you can have to create a new Tuple and then use slice notation to not include all of the elements but only some of them all right let's go I'm going to collect my name into the mycore name variable and that should be a tuple that I create by using the Tuple function and putting in my name so my name is Martin your name may be Martin or something else of course if you put in your own name this is going to look a little different than here but feel free to use my name if you want to get the exact same results next one is checking whether the character X is in the my name Tuple well let's look at the my name Tuple first actually my name looks like that it's a tuple that contains a bunch of strings that each represent one character of my name all right and now I want to check is the character X in my name I would be surprised if that was true that would be news to me okay it's not true there is no X in my name and then finally I want to create a copy of the Tuple that's excludes the first letter so I want to take all the characters starting from index one but not the character at index zero and I can do that by using the variable name that I've defined before then opening up square brackets to use slice notation and I'm going to start at index one not at index zero which is going to be the first letter of my name but that index one which is going to be the second letter and then I go all the way to the end and I can do that by putting the column and then omitting the second index that just means go all the way to the end and that's going to create a new Tuple that contains the characters a r t i n tin all right note that running this line of code created a new Tuple but I didn't save that Tuple to a variable if you wanted to continue to work with the Tuple that's the result of this slicing operation then you'd have to assign it to a variable but as this is the end of the exercise I'll keep moving on to the next one in this exercise you'll practice using python to create and edit your shopping list note that I mentioned edits so this is actually going to be about lists because remember that tbes are IM mutable but lists are mutable so you'll be able to edit this list start off by creating a list named food and it should have two elements in it rice and beans then you can append the string broccoli to food using the append method then also add the strings bread and pizza to food using the extend method and then display the first two items in the food list using slice notation and finally display the last item in food using index notation okay let's work on that shopping list here we are in idle I've pasted just the tasks into this idle session just so I I'm going to remember what are the actual strings that I need to add and which methods am I supposed to use to do it and the first one was to create a list named food with two elements rice and beans I'll start my food list by opening up and closing the square brackets and then putting two string elements in there the first one is rice and the second one is beans I'll separate them with a comma and like I said before surrounded with the square brackets and then I've got my food list looking good type of food is list that doesn't sound too tasty anyways let's keep working on this shopping list I should append the string broccoli to the food list using the append method so I will say food. append and then pass in an object and this is going to be the object to add and that should be the string broccoli enter and then the food got to not add a plus here the food list now contains rice beans and broccoli next step is to add the strings bread and pizza using the extend method so we're at this task right now so I will say food. extend and then I can pass in an iterable here as Idle nicely tells us here so I will need another list or it could be a tuple as well but I'm going to use a list and I will add to that list bread and pizza so I create a new list element that contains two strings bread and pizza and I pass it as an argument to the extend method said that I'm calling on the food object pressing enter and looking at food gives me the extended food list now it contains rice beans broccoli bread and pizza next step is to print the first two items in the food list using slice notation I can do that by using the variable name food then opening up square brackets and then I want to print the first two items which means I want to start at the beginning so I can omit the first index and just start with the colum that's going to start slicing at the beginning and I'm going to go up to index two which means that it'll go up to but not including to broccoli so we'll get rice and beans but broccoli which is at index 2 is not going to be included anymore and these are the first two items of the list so I get a list returned from slicing that contains the first two elements and again if you wanted to actually print that out from a script you just have to pass it as an argument to the print function I'll probably keep not using the print function because in here in the interactive idle shell I can just inspect the output like this and then the last task here print the last item in food using index notation so the last item I can access it with negative indexing so I can say food open up the square brackets and then pass in the index minus one which gives me the final element in the list and that is pizza all right that's the shopping list sounds like a relatively healthy meal I would say just make sure you get a good pizza and now that you've worked on such a yummy shopping list I think it's time for a long breakfast start by creating a list called breakfast from the string eggs fruit orange juice but there's a space in between which I guess is notable because you should create the list using the string. spit method okay so you got to have to think about what is the separating character or characters that you can identify in the string so that you can use do split on the string to get a list that has this three elements in it and then second task is to verify that the breakfast list actually has three items in it and you can do that using the L function and then finally you should create a new list called length using a list comprehension that contains the the length of each string in the breakfast list okay so you get to practice how to create a list from a string using the string. spit method then also just check that you did it the right way and then also write a list comprehension sounds yummy too all right take your time it's a long breakfast and then see you in the next lesson where you'll see me solve it time to cook that breakfast I'm going to start off by assigning the string that I've copied eggs fruit and orange juice to a variable breakfast uncore string equals eggs fruit orange juice and now I want to split it to create a list from that and I can use the split method to do that now I'll have to think about what's the separator that I want to split on if I just do the default it's going to split on spaces and that's going to also split between orange and Juice let's try it out just for the fun of it breakfast string dosit and I'm not passing an element in here you can see that that gives me a list that consists of X comma fruit comma orange no comma and then choose and so that's four elements which is not how you want to split it so if you use the split method it's important that you think about what is the character that you want to split on or characters because here the best would be to split on comma and space because then I think we should get the three elements that we're looking for so I will assign breakfast to breakfast string. split and then as a separator I'm going to use comma and space and now we can look at [Music] breakfast and that contains three elements eggs fruit and orange juice let's prove that these are three elements indeed breakfast the length of breakfast so if I pass breakfast to the L function then I get as an output three which means that there's three elements in that list which already completes the second task or I guess we wanted to confirm that it's three long so you could do something like saying Len and then passing in breakfast and then saying equals equals three and then we get true as a result that's another way to confirm that it's actually three elements long okay and then finally the last task was to get a list comprehension of the lengths of each element all the elements are strings which means they have a length and now I want to create a list that I'll call lengths using a list comprehension and I do that by saying equals then open up the square brackets open and close them and then inside of the square brackets I'm going to start off by first writing what I want to do to each element which is calling the Len function on it and I will pass in the breakfast item so I want to calculate the length of each breakfast item and I want to do this for breakfast item in breakfast so breakfast item is just a loop variable so you could name this anything you want to as long as you name both of the occurrences the same and this should give me a list with the lengths of each of the strings eggs is four characters long fruit is five characters long and orange juice is 12 characters long and note that also the space counts as a character in here double check that L of orange juice is 12 okay that's it we could drag it out a little more just to actually have a long breakfast here what's another way of getting the length of that list compare the lengths in the list to calling the Len function directly H I could say Len of breakfast at index 2 and I want that to be equal to lengths at index two true yay if you want to draw out your breakfast a little more you could even write a for Loop to make this comparison for each of the elements but I'm full so I'm moving on
Original Description
This is a preview of Python Basics Exercises: Lists and Tuples video course. Python lists resemble real-life lists in many ways. They serve as containers for organizing and storing collections of objects, allowing for the inclusion of different data types. You also learned about tuples, which are also collections of objects. However, while lists are mutable, tuples are immutable.
In this preview you’ll work through several exercises to practice working with Python lists and tuples.
This is a portion of the complete course, which you can find here:
https://realpython.com/courses/python-basics-exercises-lists-tuples/
The rest of the course covers:
- Working with numbers and tuples
- Sorting lists
- You will be presented with a complete challenge project to build a poetry generator, which will test all the skills you have learned in the Python Basics course on tuples and lists.
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: Prompt Craft
View skill →Related Reads
📰
📰
📰
📰
The no-code AI business stack that earns $5k/month on autopilot
Dev.to AI
GitHub’s April Changelog Exposes the Private-Repo Cost of Instant Reviews
Medium · AI
AI Did Not Kill Freelancing. It Changed What Clients Actually Pay For
Dev.to · Alcora
25 Best AI Tools in 2026 to Boost Productivity, Create Content & Make Money Online
Medium · Startup
🎓
Tutor Explanation
DeepCamp AI