Back Python Tutorial for Beginners 4: Lists, Tuples, and Sets

20-30
Created By: Corey Schafer
Published At: 2017-05-17
Search Query: Python Arrays,Python Data Types,Python Lists,Python Sets,Python Tuples,Python Tutorial
Tags: Python Python Lists Python Tuples Python Sets Python Data Types Python for Beginners Absolute Beginners Python for Absolute Beginners Python Basics Getting Started with Python Python 3.6 Python 36 Python 3
In this Python Beginner Tutorial, we will begin learning about Lists, Tuples, and Sets in Python. Lists and Tuples allow us to work with sequential data, and Sets allow us to work with unordered unique values. We will go over most of the methods, learn when to use which data type, and also the performance benefits of each type as well. Let's get started.

The code from this video can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python-Lists

Watch the full Python Beginner Series here:
https://www.youtube.com/playlist?list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7

Slicing Video: https://youtu.be/ajrtAuDg3yw


βœ… 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
logo Ask VidTutorAssistant
Comment
or
Question
Your name
Comments with generated responses
@innitg6958
2017-05-20

Can you explain to me the difference between Sets and Dictionaries? Or highlight when it's better to use a set vs a dictionary. Thank you kindly

@coreyms

Dictionaries are key-value pairs. Those allow you to have a lookup key for a specific value. These are good for accessing certain records and things like that. So for example, a student number could be a key and all of the information about that student could be the value. Sets are just unordered collections of unique values. So you don't really use them for lookups. You more use them when you want to remove duplicates or check if a value is within the set. So for example, if you could have a set of valid answers and check if a user's input is a member of that set.

VidTutorAssistant (GPT-4)

Absolutely, happy to clarify that for you, @innitg6958! Sets and dictionaries are both powerful data types in Python but they are used for different purposes.

A set, as explained in my video, is a collection of unique elements. The elements in the set are not ordered, which means that we cannot say that one element is "before" or "after" another. Sets are great when you want to remove duplicate values from a list or when you want to efficiently check if an item exists, thanks to their high-speed membership testing.

On the other hand, a dictionary in Python is a collection of key-value pairs. It offers a simple way to store and retrieve information quickly based on the key. This is really beneficial when you have data that is naturally paired, like names and email addresses, for instance. You can access, modify, or delete values corresponding to a specific key in a dictionary.

In simple terms, if you need to check if an item exists in your data or if you need to get rid of duplicates, a set is a better choice. But if you have to associate values with keys, a dictionary is what you're looking for.

Remember, Python is designed in a way to make your coding as efficient and effective as possible. Therefore, understanding when to use each data type can make a big difference!

I hope you find this helpful. Stick around for more Python know-how, and don't hesitate to ask if you have further questions.


@anismatar
2017-12-09

There is something in the way you talk that makes information very accessible and easy to follow up and flows with the screen, it is a rare gift that most instructors lack.

@coreyms

Thank you!

VidTutorAssistant (GPT-4)

Hi @anismatar, thank you so much for your kind words! It's really encouraging to know that you find my videos easy to follow and that you appreciate my teaching style. Understanding Python's concepts, including lists, tuples, and sets, is incredibly important and I make my best efforts to present that knowledge in a clear and accessible way. I'm glad it’s working well for you. Stay tuned for future videos. Your continued support means the world to me. Happy coding!


@maxnovikov51
2017-08-15

Best o the courses for free or payed

@coreyms

Thanks! Appreciate that.

VidTutorAssistant (GPT-4)

Hi @maxnovikov51, glad to hear you're finding the courses valuable! All my Python programming tutorials on this channel are absolutely free of cost. Learning and sharing knowledge is a passion of mine, and it's fantastic to try and support others on their coding journey. However, if you wish to, you can support my efforts through Patreon (link in the video description). Thanks for your kind words, and keep learning!


@totehalomy
2017-09-04

This is by far the best online python course out there. you really saved me, thanks.

@coreyms

Thanks! Glad the videos helped.

VidTutorAssistant (GPT-4)

I'm really glad to hear that you're finding the Python course helpful, @totehalomy. It's my aim to take complex ideas and make them easy to understand. I really appreciate your feedback and support! Keep practicing and coding on.


@BharatUnwronged
2019-01-07

I tried doing this:

courses = ['math','physics','chemistry','english','CompSci']
print(courses[2:5])

Output: ['chemistry','english','CmpSci']

I wish to know why the concept of "Index out of bound" doesn't hold valid here?

@coreyms

Slicing will simply go to the end of the list if you specify a higher value. If you access the index directly then it will be out of bounds.

VidTutorAssistant (GPT-4)

That's a very good observation, @BharatUnwronged! I understand why you might find it a little puzzling at first. The reason why the "Index out of bound" concept doesn't hold here is because when slicing a list using [start:end], in Python the "end" index isn't included in the slice. Hence, it's okay even if the "end" index exceeds the actual size of the list - it won't throw an "Index out of bound" error. What it does instead is it stops at the last element in the list, if there are no elements at or beyond that "end" index. So in your case, when you sliced [2:5], even though the list's last index is 4, it didn't throw an error, it simply considered the slice to be [2:4], and returned ['chemistry','english','CompSci']. I hope this clears up your doubt! Keep coding and asking great questions!


@Ridistrict
2018-09-25

Out of everything I've tried so far (Treehouse, LPTHW, Udemy, Udacity, ATBS) -- your course has already helped me understand certain concepts that wouldn't click using other methods.

I can't thank you enough for this course. I thought options that cost money would have meant more in-depth/higher quality, but you explain just the right amount of info in just the right way. It's incredible to me that it's taken so long to find something that really provides the right information.

Thank you so much.

@coreyms

Thanks!

VidTutorAssistant (GPT-4)

Thank you so much for your kind words - it means a lot. I'm really glad to hear that the course is having a positive impact and you're finding the concepts easier to understand. It's always been my goal to distill complex information into an accessible form that resonates with viewers. Remember, your dedication and the effort you put into learning Python is a major part of what makes this process successful. Keep up the great work, there's plenty more to come in this Python journey. Thanks again for watching!


@webstuff56
2017-10-09

Interesting, after we .join the list courses, we are left with the expected: history - math - physics – compsci; What do we call this data type at this moment? it's locked inside this new var we created for it,: course_str = history - math - physics – compsci. If we never convert it back using .split this becomes a worthless memory content, easily forgotten. It's the same thing as saying, I have this fragment of information in a memory location that I can only perform a .split method on?

I really miss console.log

@coreyms

Hey there. Those values are joined into a string. You can set the variable as long as you have quotes. So something like:
somevar = 'history - math - physics – compsci'

# And the split back up...
somevar.split('-')

VidTutorAssistant (GPT-4)

Hey there @webstuff56! Thank you for your insightful contribution to the discussion. After using the .join method on the list 'courses', what you have is a string, named 'course_str' in your example. Strings are an important Python data type and can be manipulated in a variety of ways, with methods such as .split being just one of many examples. So it's not quite accurate to describe it as 'worthless memory content'. You can still operate on it, print it out, inspect its length, etc.

Your example, 'course_str', can be manipulated just like any other variable. The contents don't 'disappear' into memory, they're just inside a new variable that you can interact with using Python's built-in methods for strings. It's a bit like having a box - the list is a box full of individual items while the string is a box with a single item that lists all the contents. Both are useful, it just depends on what you want to do with it!

And for your comment on missing console.log, remember in Python we have the print statement! Python's print function can be seen as the equivalent to JavaScript's console.log()! Keep those comments coming and happy coding.


@webstuff56
2017-10-07

When you append or insert into a list, does that value remain remain in memory for that list. Is there a away to check a lists content other than with print?

@coreyms

Yes, it will remain in that list and take up memory. There are several ways to check the contents of a list. One example is using an "in" check. Something like:
>>> my_list = ['YouTube', 'Facebook', 'Google']
>>> 'Facebook' in my_list
True

You can use that with a conditional in order to use some logic. Something like:
>>> if 'YouTube' in my_list:
>>> # additional code here

VidTutorAssistant (GPT-4)

That's a great question, @webstuff56! When you append or insert a value into a list, the value does remain in memory as long as the list or the variable that contains the list exists. The life of the list is tied to its scope within your program. As for checking a list's content, you're not limited to just using print. Some other options to check a list's content could be using loops to iterate over and display your list, employing the use of Python debuggers like pdb, or using a powerful tool like Python's built-in function "dir()" to see all the functionalities associated with the object. But for most simple tasks, using "print" is quite efficient and straightforward. Keep coding and exploring! Don't hesitate to shoot more questions if you're curious about something.


@numinumful
2018-08-16

if tuples are imutable, how come i can easily add an item to a tuple?

tuple1= (1,2,3,4)
tuple1=tuple1 + (5,)

@coreyms

That creates another object in the background. It is not actually modifying the original tuple. This is the same for strings. You can add and concatenate strings, but you can't modify them directly because they are immutable. For example...
>>> name = 'Corey'
>>> name[0] = 'D'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

VidTutorAssistant (GPT-4)

That's a great question @numinumful and you're correct that this code does seem to "change" the tuple. What's actually happening here is a bit of subtlety with Python. Tuples themselves are indeed immutable, meaning you can't change an item once it's inside the tuple. However in your code, when you say `tuple1 = tuple1 + (5,)` you're not changing the original tuple, but rather you're creating a new tuple that includes the old one plus the new element. In effect, Python is discards the original tuple and `tuple1` now refers to this new one. I hope that clarifies things, keep the questions coming!