Starting With Python Tuples: Python Basics

Real Python · Beginner ·🛠️ AI Tools & Apps ·2y ago

Key Takeaways

The video introduces Python tuples, covering their definition, creation, and properties, including immutability, indexing, slicing, and iterability, using tools like IDLE and Python.

Full Transcript

welcome to this python Basics course about tuples and lists you've learned about a bunch of fundamental data types at this point you've learned about strings integers and floating Point numbers for example but what if you want to describe a collection of elements how do you combine several fundamental data types into something that's more complex or from another perspective what if you have a bunch of lonely animals I mean elements don't you just want to hug them all together H well there are certain data structures in Python that can model such a collection of data for example a list of numbers you can have student names that are enrolled in a class or a row in a spreadsheet or similarly a record in a database or of course all your favorite animal emojis woof in this course you'll learn how you can work with Tes and lists when you want to use which of these two collections as well well as what mutability is and why it's important to think about it currently you are in the overview of this course you'll then move on to tupes then lists and then we'll wrap up the course with a summary to expand on this table of contents a bit on this slide you can see all the many topics that you're going to cover first about tuples and then about lists now there's a little bit of background which is that I'll be using idle in this course if you're following Ong with the python basic series then you're already familiar with this tool if not then here on this slide you can see a couple of additional resources that you can use to study up on idle if you want to but you don't need to know anything about idle you can work through this course with any code editor or repple session that you want to and that's it for the overview so next let's get started learning about tup let's get started talking about tuples or immutable SE sequences and I want to start off this part of the course by helping you to find a way to think of tupal as rows let's start off by how do you even pronounce this word there's actually two valid pronunciations of the word Tuple the first one is the one I just said Tuple so you would pronounce it like in the word quadruple and another one is tle like in the word quintuple both of these pronunciations are fine and both are used throughout the python community so you can pick either you can mix and match or you can just settle on one of those it seems like eventually I settled on calling them tuples even though I remember also talking about them as tles sometime in the past and I may end up throwing in a tle here or there during this course just to make sure that everyone's happy or everyone's unhappy I don't know both of these pronunciations are fine and refer to the same thing in Python now what is that thing in Python what is a tupal a Tuple is a finite ordered immutable sequence of values that's a mouthful it gets worse python borrows the name and the notation from mathematics which means per definition each element is separated by a comma inside a tuple and all the elements are surrounded by a single pair of parentheses this is a tuple that contains three elements in Python that would be three integers 1 two and three okay so that's maybe the definition but it's not super helpful to really understand what a tupal is so I want to give you some help in Remembering an approximation of how you can think about a tuple in Python it's very helpful to think about database records in that context or rows in a spreadsheet you may have worked with some sort of a spreadsheet application before you have some sort of idea of what a spreadsheet looks like and that it consists of multiple columns and multiple rows here in this example you'd see an employees sheet that has three columns employee ID name and role and then it has three rows that each contain data you could think of a python Tuple as one row in the spreadsheet or one record in the database right so the first row here you could represent it as a python Tuple as shown at the bottom of this slide so here you would surround the information that is given in the row with parenthesis and separate each of the values in each column with a comma so the first one is the employee ID which here has the value one so you would put in an integer as one separated with a comma from the next value the next one is the name in this case Adisa and that would be a string in Python so you would write out the string Adisa put a comma again and then you're in the third column that's the role and in this case she's a software engineer so you would put this words software engineer also as a string in python as the third item in the Tuple so while this isn't a perfect explanation of what a tuple is it's a pretty good approximation if you think of a tuple as a readon database record so one of these rows but readon why is that a readon database record is a finite sequence of values it ends at some point it has a fixed structure you usually don't change these columns around very much it has fixed values that is if it's read only and it contains a variety of data types in the one you saw before you saw some text and you saw some numbers and it also usually contains related data so each row the data that is in the different fields is related to each other and if you keep that in mind that a tuple is kind of like a read only database record you have a good chance of using them in the way that they're intended in Python again if you walk away from this course and in the evening you remember that you've heard something about tuples but you're like what was this thing again t tle then I want you just to think ah all right it's a readon database record and if that approximation gives you some sort of an idea then I think you've got a better grasp on how to think about tupal in Python that is what a tupal is and you'll explore them in much more detail in the following lessons in the next one you're going to learn how you can create a tuple in Python in this lesson you'll learn how you can create a tuple in Python you'll learn about two ways tupal literals and you learn about the buildin Tuple function before we go to tupal literals though here's a quick throwback to string literals you can create strings by just surrounding characters with quotes either single quotes at the beginning at the end or double quotes at the beginning at the end and both of these create a string literal now I'm mentioning this because tupal and strings have quite a lot of things in common as you'll see in the upcoming lessons a string literal you surrounded by quotes and a tuple literal are comma separated values that are surrounded by parentheses this is a tuple literal that starts with parenthesis and ends with a parenthesis and in between it has multiple values that are separated by commas these values can be of any type they don't all have to be integers like in this first example but they can be a mix of strings and integers and floating Point numbers really any python data type that you can think of here is another tle that you've SE before this would be maybe one employee and the record in the database where you can see the first value is an integer and then you have two strings following that and it's all surrounded by a parenthesis and each of the elements are separated by commas this is how you create a tuple literal let's go ahead and try that out in idle all I did was start with a parenthesis then can type in as many values as I want to and when I press enter you can see that here you get a tuple back out and let's double check that it's really a tupal so I'll assign it to a variable that could be maybe vinning positions in a race one two three only the first three get a medal and now we can look at winning positions I can see that that's this Tuple one two three and to prove that it's actually a tuple I'm going to pass it as an argument to the type function and then python tells me that this is indeed of the class Tuple the second one that you've seen in the slides would be maybe an employee of your company and that's the first employee her name is Adisa and she's a software developer you end the Tule by closing the parentheses again and here you go you've got your employee Tuple and again let's double check that it is indeed a tuple even though it contains all sorts of different data types here again this is a tuple so this is a way that you can create a tuple literal you use the parenthesis and you separate it by commas I'll tell you a little secret it's not so much of a secret but the parentheses are actually optional what makes a tupal are the comma separated values so I could create the same Tuple all without the parenthesis at the beginning at the end let's just do an example one 1 2 3 if I just type it in like that I also get a tuple as a result so assign it again to numbers one two three and the type of numbers is going to be a tuple and also you see if I just type in numbers then python prints the output with the parentheses around it because this is how Tes are represented but when you define a tup leral you don't need to put the parenthesis there however I would suggest to always do it because it makes it more clear what you're actually creating here so this is how you create a tuple literal another way of creating a tuple is by using the buil-in Tuple function with this you can pass in another sequence type and create a tuple from that now what's another sequence type that you've already encountered those are the strings that I mentioned before so you can pass in a string to the Tuple function and python will create a tuple for you let's try that out in idle as well let's assign it to something word equals Tuple and then I pass in a string that says python then you will see that what I get as a result is a tuple a tuple that consists of all the elements of the string sequence so remember that strings are sequences of characters and what the Tuple function does is it splits it up into the characters that the string consists of and assigns them each as an element in the Tuple so this is the second way that you can create a tuple from another sequence type by using the Tuple function keep in mind that this needs to be a sequence type so if you try to call Tuple and pass it for example an integer then you'll get an error because the integer object is not iterable so the argument that you pass to the Tuple function needs to be iterable or a collection all right so this is how you can define a tuple and next up I'll continue to compare tupes and strings a bit more because you'll see they have quite a bit in common and if you have somewhat of an understanding of strings it'll help you to better understand tuples as well previously I've mentioned that tupes and strings have things in common now in this lesson we'll go a little bit deeper into this comparison between tupes and strings I'll start off by showing you some similarities between tupes and strings let's start with an overview tupes have a length tuples support indexing and slicing tupes are immutable and tuples are iterable all of these things they have in common with strings side off by looking at the length of a tupal just like with the string you can call the Len function and pass it a tupal and as a result you'll get how many elements are in the Tuple let's try that out in idle so you've seen a numbers Tuple that just points to one two three and then we can pass it to the Lend function and you can see that as an output you get the number three now let's compare it to uh string right we worked with the word python before and the word python has also a length of six now you could even turn the word python into a tuple because a tuple can consist of any sort of data type so it doesn't have to be integers It Could Be Strings so what we did before was to split up the word python into its characters each a separate string and make them the elements of a tupo let's do that again I'll call it the word Tuple and just pass our word to the Tuple function and now we have word Tuple consisting of the separate characters of the word Python and this also has a length right so this should be the same length as the word and here you go it consists of six characters just like the string python consists of six characters further each element in a tuple has a numbered position called an index that's also the same as it is with strings so I can access individual elements through their index and you do that by placing the index number inside of a pair of square brackets right after the Tuple you've probably done this with strings before but here's an example again with the numbers list here we've defined a tuple called numbers which consists of three elements one two and three and then in the next line you're accessing the element at index position one and that is the number two as an output you're going to get the number two and note that the index count starts with zero like in most programming languages so one is at the index zero two is at index one and three is at index two which is why when you access the element at index one you get back out the number two so just a quick recap of indexes or indices you can use either of the plurals it's just like tle and Tuple huh here's a string and the relevant indexes for the characters in the string the letter P would be at index zero the letter Y would be at index one Etc up to the N the last letter of the word python which is at index five the same goes for Tuple indexing so if you think of an expanded numbers list that has the first three numbers under 10 and then the last three numbers under 10 so it consists of 1 2 3 7 8 and nine then you'd find the number one at index zero the number two at index one Etc and at index five you'd find the number nine in this case also python supports negative indexing which means that you can go backwards this is also the same as with strings so you can access the integer 9 in this example Tuple also by using minus one as the index number in square brackets and all the way backwards so that you could access the first element in this specific Tuple by passing minus 6 as the negative index now maybe this sounds a little abstract so let's try it out again in idle I'll work with word and word Tuple so if you remember string indexing I'll access the P the first element by passing in zero you can see that I get out the p and with word Tuple I can do the exact same thing word Tuple open up the square brackets put in the zero close the square brackets and again I get the P now let's take a look at something in between maybe we want to get out the T of P so in the word Tuple I can pass in the index position that would be p is at zero y is at one and T is at two so if I pass in two as the index number I'll get out the T and again this is the same if you do it with the string and finally also the negative indexing so if you want to get the last element here you could pass in the index number five but you could also go backwards and say word score Tuple open up the square brackets and then pass in minus one this is going to give you the last element in the Tuple and in this case that's an N now you may think okay so that's exactly the same as with the string what's the point well the point is tup can't only just contain characters they can for example also contain numbers so we have this numbers tle right and you can do the same thing that you did with the string elements in a Tule also with numbers so I can access the last element of the numbers Tuple by passing in minus one and this will give me the number three as an output so tupal and strings both support indexing tuples also support slicing so I can extract portions of a tuple just like you can do with a string by inserting a column between two index numbers for example here with square brackets 0 column 2 closing square brackets you would slice out the first two items of a tuple or here let's look at another numbers list for example the OD numbers under 10 would be a tuple that consists of 1 3 5 7 and n and if you were to slice out just five and seven you could use the notation square bracket 2 column 4 let's try that out in idle so here I'll Define the odd numbers list and now let's do some slicing on it odd numbers starting from two up to but not including four is going to give me five and seven the index always starts at the lower index and includes that one and then goes up to but doesn't include the ending index that you put on the other side of the column so we start at 0 one two we start here at the number five and then this is index 3 is number seven that's included in the slice and nine would be at index 4 and this is where it stops and it doesn't include the stopping index anymore so you get five and seven as the slice from this odd numbers list can do the same with a string as well so word is our python string and here you can slice out see what we get if we do two and four here you get a T and H and it works in the same way to recap the slice XY starts from the element at index X and the slice goes up to but does not include the element at index y another thing that they have in common with strings is that tupal are immutable which means that you can't change the value of an element in the Tuple after creating it just like you can't change a single character in a string once you've created the string so if you tried to do an item assignment for example here we have the numbers Tuple and you're attempting to replace the first element with the integer two then you get a an error because this just doesn't work let's try it out life we still have the numbers tle here available so I'll try to change the final element minus one and I will try to assign it to the number 100 just as expected I get the type error that the Tuple object does not support item assignment again let's compare it to the string you'll get the same so if I wanted to change the first letter of python to make it say maybe tython python protects itself from something like that no it's just the same reason as with the Tuple is that strings are immutable so the string object does not support item assignment and finally another similarity between tuples and strings is that tuples are iterable which means you can Loop over them let's try that out so I can keep working with the numbers Tuple here and I can say for each number in numbers print the number and you can see that it's iterable and python can access each element of the Tuple separately and then prints it out first one then two and then three so same with a string for character in word I can print out the character and then python prints out each separate character of the string Python and there's another thing where tobes and strings are similar which is that they're iterable just like any collection in Python and this concludes our little Excursion about the similarities between tupes and strings in our next lesson we're going to look at Tuple unpacking and I'll show you what you can do with that

Original Description

This is a preview of Python Basics: Tuples and Lists video course. It provides an introduction to working with tuples. You can use them to store and organize a collection of objects, which can be of any data type. Instead of just storing one item, a tuple can hold multiple items. Tuples are immutable meaning you can’t modify them after you’ve created them. You'll also learn about similarities with Python strings. This is a portion of the complete course, which you can find here: https://realpython.com/courses/python-basics-lists-tuples/ The rest of the course covers: - What lists and tuples are and how they’re structured - How lists and tuples differ from other data structures - Changing elements in a list - Nesting of lists - Shallow vs Deep copies using lists - How to define and manipulate lists and tuples in your Python code
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 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

This video introduces Python tuples, covering their definition, creation, and properties, and provides hands-on examples using IDLE and Python. By the end of this lesson, you'll be able to create and manipulate tuples in Python.

Key Takeaways
  1. Create a tuple in Python using parentheses and commas
  2. Use the Tuple function to create a tuple
  3. Access elements in a tuple using indexing
  4. Slice a tuple to extract a subset of elements
  5. Loop over a tuple to print each element
  6. Use IDLE and Python to practice working with tuples
💡 Tuples are immutable sequences of values in Python, similar to strings, and can be created, indexed, sliced, and looped over.

Related Reads

Up next
Make Stunning Tree Diagrams with ChatGPT In Seconds!
Educraft
Watch →