Python Tutorial: Namedtuple - When and why should you use namedtuples?

Corey Schafer · Beginner ·🛠️ AI Tools & Apps ·10y ago

Key Takeaways

This video tutorial covers the use of namedtuples in Python, a high-performance container datatype that offers a compromise between tuples and dictionaries in terms of readability and functionality. The tutorial explains how to create and use namedtuples, their advantages over regular tuples, and how they can improve code readability.

Full Transcript

hey how's it going everybody in this python video we're going to be taking a look at named tupal and what named tupal are and why we would use them um so you can think of a name Tuple kind of like a lightweight object that uh works just like a regular Tuple but it's more readable um so what do I mean by this so say that we want to represent uh RGB color values red green blue color values in code and say that we choose a tupal to do this so here is a regular tupal so we have color equal to and this will be our red uh 55 will be our red 155 will be our green 255 will be our blue so let's say that we wanted to print out the red value so in order to print out that red value we would just do print color and then we would do index of zero and if we run that code then you can see that we got 55 for the red value now what's going to happen here is that someone else is going to come and look at this code or even you could come and look at this code weeks and months later and they're going to read this and they're not going to know what's going on we have color equal to these numbers and then we're printing out uh the index of zero you know what are these numbers somebody could look at this and think you know is this H saturation and light or I don't know what's going on here so it would be really nice if this was more readable now the first idea that might pop into your head is to use a dictionary um so let's see what that would look like so let's grab a dictionary representation of this and let's paste this in here now instead of printing out this index of zero down here uh let's print out red and let's save that and if we run it you can see that we got the same thing it's 55 so what is wrong with this why wouldn't we choose to use a dictionary uh well first of all maybe we chose to use a tupal for a reason um so T pools are immutable um which means that you can't change the values maybe that's something that we wanted um and also dictionaries uh require a little bit more typing here so if we made more than one color we'd have to come in and type all this out every time we created a new color so a named tupal is kind of a good compromise between the tupal in the dictionary uh between readability and also it gives you the functionality of a tupal so let's go ahead and see what this would look like um so let me copy the example I have here and paste this in and let's go ahead and go over this and for now I'm going to go ahead and take out these values here okay so first of all to use the name Tuple uh first we have to import it so from collections import name Tuple and then this line here is the syntax that we use for name tupal so we'll do that we want a color equal to name Tuple and then the name of our name tupal and we'll do this as color I have all this typed out up top but I just want you to see uh if you are making one your yourself the steps here so the name tupal is named color and then these are going to be the values of the tupal so the values that we want for our tupal are red green and blue so that's what the syntax looks like to create a name Tuple now let's take a look at the advantages over a regular tupal here now if you remember when we created a regular tupal uh we just did the values like this and it wasn't very readable and now we are saying that we want this variable color equal to color which is what we called our name Tuple here and right now we have 55 155 255 and that is red green and blue now I can still use this just like a regular tupo if I wanted to come in here and I wanted to do the in print the index of zero which would be our red value then I can print that and it prints out 55 but um I can also come in here and print these out by name so I can say color. red and print that out and you can see that it's 55 now you can see this is already a lot more readable than our regular tupal because whenever we come in here or somebody else comes in and looks at our code they're going to see okay they're printing out color. red so and then they're going to look up here and say okay this is a color uh with three values here and they can make a guess as to what that is now if you want to be really explicit you can actually come in here and uh add all these values in so that whenever you come back uh you know EX actly what those values are but even without those there um somebody's going to be able to come in and see okay uh you created this from uh this color here and then they can look back at the name tupal where you made that definition and they can see that it's red green and blue uh with the regular tupal you didn't have that that was that information was nowhere to be found and now if you remember also it's this is a lot less typing as well if you remember our dictionary here every time if we were to make a new color or something like that and I'll just call this something else so it doesn't collide with our other one so with our dictionary this uh we had all this typing to do uh but if I wanted to make another color from a name tupal then I don't have to type out all this stuff I can just do okay I want a color and white would be 255 255 255 and that's done and then later in the code if I wanted to print out um say the blue value of white then I would just do white. blue and you can see that that is 255 and uh that's also a little bit easier to write than the dictionary if you remember the dictionary we can't do this do syntax we'll get an error uh we have to put that in Brackets which isn't a big deal but it's a lot more typing it's a uh lot easier just to come in here and use the do syntax so hopefully that kind of clears up what a name tupal is and why exactly you would use one and also hope you can see how this is a lot more readable than what a regular tupal might be so whenever um someone else read your code or whenever you come back to your code in a couple of weeks or months uh then you're going to be able to take a look at this and see almost instantane instantaneously what's going on and with the regular Tuple example that we used um that would have been really hard so yeah I hope that cleared any uh questions that you had about name tupes um if you do have any questions then just ask in the comment section below um be sure to subscribe for future python videos and thank you guys for watching

Original Description

Named Tuples in Python are High-performance container datatypes. What advantage do namedtuples have over regular tuples and when should you use them? In this video, we'll take a look at namedtuples and why you should use them. The code from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/NamedTuples ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Corey Schafer · Corey Schafer · 39 of 60

1 Web fonts using CSS Font Face
Web fonts using CSS Font Face
Corey Schafer
2 Using Font Awesome in Desktop Applications (OS X)
Using Font Awesome in Desktop Applications (OS X)
Corey Schafer
3 Sublime Text 2: Setup, Package Control, and Settings
Sublime Text 2: Setup, Package Control, and Settings
Corey Schafer
4 ArcGIS API for JavaScript Part 1: Our First Web Map
ArcGIS API for JavaScript Part 1: Our First Web Map
Corey Schafer
5 Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Corey Schafer
6 Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Corey Schafer
7 ArcGIS API for JavaScript Part 2: Starting Templates
ArcGIS API for JavaScript Part 2: Starting Templates
Corey Schafer
8 Paver Patio Time Lapse
Paver Patio Time Lapse
Corey Schafer
9 Mac Tip: Ways to perform Screen Capturing and Screenshots
Mac Tip: Ways to perform Screen Capturing and Screenshots
Corey Schafer
10 WordPress Plugins: Imsanity
WordPress Plugins: Imsanity
Corey Schafer
11 WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
Corey Schafer
12 Sublime Text 3: Setup, Package Control, and Settings
Sublime Text 3: Setup, Package Control, and Settings
Corey Schafer
13 Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Corey Schafer
14 Mac Tip: Adding Folder Stacks to the Dock
Mac Tip: Adding Folder Stacks to the Dock
Corey Schafer
15 CSS Tips and Tricks: Add External URLs to Print Stylesheets
CSS Tips and Tricks: Add External URLs to Print Stylesheets
Corey Schafer
16 JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
Corey Schafer
17 JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
Corey Schafer
18 JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
Corey Schafer
19 JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
Corey Schafer
20 JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
Corey Schafer
21 JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
Corey Schafer
22 JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
Corey Schafer
23 Python Tutorial: if __name__ == '__main__'
Python Tutorial: if __name__ == '__main__'
Corey Schafer
24 Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Corey Schafer
25 How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
Corey Schafer
26 Easily Resize Multiple Images Using Picasa
Easily Resize Multiple Images Using Picasa
Corey Schafer
27 Easily Resize Multiple Images Using the Mac Terminal
Easily Resize Multiple Images Using the Mac Terminal
Corey Schafer
28 Python Tutorial: virtualenv and why you should use virtual environments
Python Tutorial: virtualenv and why you should use virtual environments
Corey Schafer
29 Python Tutorial: pip - An in-depth look at the package management system
Python Tutorial: pip - An in-depth look at the package management system
Corey Schafer
30 Git Tutorial: Using the Stash Command
Git Tutorial: Using the Stash Command
Corey Schafer
31 How Software Engineers, Developers, and Designers can volunteer their skills
How Software Engineers, Developers, and Designers can volunteer their skills
Corey Schafer
32 Git Tutorial: Diff and Merge Tools
Git Tutorial: Diff and Merge Tools
Corey Schafer
33 Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Corey Schafer
34 Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Corey Schafer
35 Python Tutorial: str() vs repr()
Python Tutorial: str() vs repr()
Corey Schafer
36 Programming Terms: DRY (Don't Repeat Yourself)
Programming Terms: DRY (Don't Repeat Yourself)
Corey Schafer
37 Programming Terms: String Interpolation
Programming Terms: String Interpolation
Corey Schafer
38 Programming Terms: Idempotence
Programming Terms: Idempotence
Corey Schafer
Python Tutorial: Namedtuple - When and why should you use namedtuples?
Python Tutorial: Namedtuple - When and why should you use namedtuples?
Corey Schafer
40 Programming Terms: Mutable vs Immutable
Programming Terms: Mutable vs Immutable
Corey Schafer
41 Python Tutorial: Else Clauses on Loops
Python Tutorial: Else Clauses on Loops
Corey Schafer
42 Overview of Online Learning Resources
Overview of Online Learning Resources
Corey Schafer
43 Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Corey Schafer
44 Git Tutorial for Beginners: Command-Line Fundamentals
Git Tutorial for Beginners: Command-Line Fundamentals
Corey Schafer
45 Quickest and Easiest Way to Run a Local Web-Server
Quickest and Easiest Way to Run a Local Web-Server
Corey Schafer
46 Python Tutorial: Generators - How to use them and the benefits you receive
Python Tutorial: Generators - How to use them and the benefits you receive
Corey Schafer
47 Python Tutorial: Comprehensions - How they work and why you should be using them
Python Tutorial: Comprehensions - How they work and why you should be using them
Corey Schafer
48 Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Corey Schafer
49 Programming Terms: Combinations and Permutations
Programming Terms: Combinations and Permutations
Corey Schafer
50 Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Corey Schafer
51 Preparing for a Python Interview: 10 Things You Should Know
Preparing for a Python Interview: 10 Things You Should Know
Corey Schafer
52 SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
Corey Schafer
53 SQL Tutorial for Beginners 2: Creating Your First Table
SQL Tutorial for Beginners 2: Creating Your First Table
Corey Schafer
54 SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
Corey Schafer
55 Linux/Mac Terminal Tutorial: Navigating your Filesystem
Linux/Mac Terminal Tutorial: Navigating your Filesystem
Corey Schafer
56 Python: Ex Machina Easter Egg - Hidden Message within the Code
Python: Ex Machina Easter Egg - Hidden Message within the Code
Corey Schafer
57 Mac Tip: New Split Screen Feature in El Capitan
Mac Tip: New Split Screen Feature in El Capitan
Corey Schafer
58 Setting up a Python Development Environment in Eclipse
Setting up a Python Development Environment in Eclipse
Corey Schafer
59 Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Corey Schafer
60 SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
Corey Schafer

This video tutorial teaches how to use namedtuples in Python to improve code readability and offers a compromise between tuples and dictionaries. Namedtuples are immutable, high-performance container datatypes that can be used to represent structured data.

Key Takeaways
  1. Import the collections module
  2. Create a namedtuple using the namedtuple syntax
  3. Use the namedtuple to represent structured data
  4. Access namedtuple fields by name or index
  5. Create multiple namedtuples with different values
💡 Namedtuples offer a compromise between tuples and dictionaries in terms of readability and functionality, making them a useful data structure in Python programming.

Related AI Lessons

Up next
Salesforce Flow New Features (Summer '26) | Open Record, URL & Show Toast Messages
AITECHONE
Watch →