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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there how's it going everybody in this video we'll be learning about lists tuples and sets in Python now listen to polls allow us to work with sequential data and sets our unordered collections of values with no duplicates and we'll look at all of these to see exactly what that means so first let's look at lists and we're going to spend a majority of the time on lists just because it has a lot more functionality than the other data types so just like the name implies it allows us to work with a list of values so for example let's say that I wanted a list of courses so I could create a variable here called courses and to create a list we're going to use these square brackets and within these brackets we put each value that we want separated by a comma so for example let's say that we wanted a list of courses so I'll say history and math and physics and also lastly we'll put in Comp Sci so now if we print out this list so I'll print out courses and run that and we can see that it prints out our entire list now if we wanted to see how many values are in our list then we can get this by using the le n function which stands for length so if instead we print out the length using le n of courses and run that then you can see that it says that we have four values and our list and we can access each of these values individually so first let's go back to just printing out our list and running that so now to access the values in our list we can use square brackets after our list and pass in the location of the value that we want so we can put in square brackets and this location is called an index and it starts at zero so to access the first value of our list we can access the location at index 0 if I print that then we can see that we get history well since the length of our list is 4 that means with the first value starting at index 0 then the last value will be at index 3 so it's our total length minus 1 so let's say I wanted to grab the last value for my list which is comps I could count these indexes out and see which one should be able to access it so 0 1 2 & 3 the third index so if I print out courses 3 and access that index of 3 and run that then we can see that we printed out comps I now we can actually use negative indexes 2 and negative indexes we'll just start from the end of the list so since 0 is the first item of our list I can also get the last item of our list using a negative 1 so if we print out courses index of negative 1 and run that that we can see that we got comps I again which is the last item it's more convenient a lot of the time using a negative 1 to get the last item because we don't have to worry about what the length of the list is so for example if my list grew by 10 items then the third index would no longer be the last item but the negative one will always be the last item and also if you accidentally try to access an index that doesn't exist then you'll get an index error so in this example if we tried to access an item at index 4 and run that since there is no index 4 you can see that we get this list index out of range now instead of only grabbing one value where you can also access a range of values so if I wanted to grab the first two values from this list then I could say that I want to access starting at index 0 and go to but not including index 2 so this first index is our starting point and the second index which is separated by this colon is the stopping point now one thing that's a little confusing is that the first index is inclusive but the second index is not and there's good reasons for that but it's easy to forget so what we're saying here is that we want all of the values between the beginning and up to but not including the second index so if we run this and we can see that it printed out history and math because it printed out 0 & 1 all the way up to 2 but not including 2 which is physics now since our first index here is just the start of the string we can actually just leave that off and it will assume that we want to start at the beginning so if we said print the courses with nothing there : - and run this and you can see that we get the same result because it just assumed that we wanted to start at the beginning now if we just wanted to grab physics and Comp Sci from this list then we can say that we want to start at index two and then put in our colon and now just like our starting index if we don't put anything here and it's going to assume that we want to go all the way to the end of the list so if I run this and you can see that it printed out physics and Comp Sci as it started that our second index which is physics and just went all the way to the end now what we're doing here is called slicing and if you'd like to learn more about slicing in depth then you can watch my detailed video on that which shows you how you can skip values go in reverse and things like that and I'll leave a link to that video in the description section below ok so let's look at some list methods that we have available to us that allow us to modify our list so first let's say that we wanted to add an item to our list there are a couple of ways we can do this so first if we just wanted to add an item to the end of our list then we could use the append method so let's say that we want to add art to our courses so we can just say courses dot append and we want to append art so now if I remove this slicing and just print out our courses list and run that then you can see the art was appended here to the end of the list now if we wanted to instead add art to a specific location in our list then we could instead use the insert method now insert takes two arguments first it takes the index where you want the to insert the value and then the value itself so if I wanted to insert art to the beginning of our list then we could say courses dot insert and now the first argument is the location so let's just say location 0 which is the beginning and then the value that we want to insert which is art so if we run this now we can see that art was inserted at position 0 now that only inserted the value it didn't overwrite anything so you can see that all the other courses are still here but they just got shifted now another way of adding values to our list using the extend method now sometimes this confuses people so let's look at what this does so we want to use extend when we have multiple values that we want to add to our list so for example let's say that we have another list here called courses - and we'll set this equal to another list with art and education in this list and we want to add these values to our original courses list so first let's see what happens if we use this insert method so instead of inserting art to the beginning of our list let's instead insert these courses to the beginning of our list so let's go ahead and run this so we can see that at the beginning of our list that it actually added the entire list of courses - and not each individual value so we can actually have a list within a list like we have here so if we were to print the first value of our courses list so I'll print out the index of 0 and run that then we can see that now the first value is actually this list itself but this isn't really what we wanted we wanted to add all of those values from our second list to our original list now that is why we use the extend method so let's go ahead and set this back to the way it was to just print the courses now instead of inserting here will instead use extend and it only takes one argument which is the iterable so we will extend courses with courses - so now if we run this and we can see that when we did courses extend with courses - that it added the values from our second list here to our original so a lot of people get that mixed up with append and extend so again if you were to append it just like with insert then it's just going to append the list itself on there instead of the each individual item so if we use extend and now we can see that each individual item is extended onto that list ok so now let's look at how we can remove some items or remove some values from our list now one way to remove values is to just use the remove method so if we were to say courses dot remove and let's say that we wanted to remove math so if we save that and run it and we can see that math was removed from the courses list now there's also a way of removing values with this pop method so if we say courses dot top now by default this will remove the last value of our list now this is useful if we want to use our list like a stack or a queue so if we run this like it is then we can see that comps I was pop of our off of our list and now we just have these three courses now one other thing about pop is that it returns the value that it removed so we can actually set a variable and grab that return value so if I set a variable here and say poped equals courses pop and then I was to print this above our courses here and run that that we can see that it grabbed that comp site value that was popped off at the list so if you had a stack or a queue then you could go through and just keep popping off values until your list is empty okay so now let's look at how we can sort our list in a couple of different ways here so first of all let's say that we just wanted to reverse our list as it currently is now this is pretty easy so we can just use the reverse method so I can say courses dot reverse and if we run this and we can see that now it prints out our courses but in Reverse so the last item all the way up until the first item now instead of reversing our list what if we wanted to sort our list now sorting is just as easy we can just use the sort method so I'll save that and run it and you can see that now our list is sorted in alphabetical order so comps I history math physics now if our list contained numbers that it would sort those in ascending order so let me call create another list here of numbers I'll just call that numbs I'll set this equal to some random value cell say 1 5 4 and 3 and we'll save that now below course we will just say noms dot sort and we will also print these out so I'll grab that variable print those out and run that so now we can see that our strings were sorted alphabetically and our numbers were sorted in ascending order now what if we wanted our values sorted in descending order now one way you might think to do this is just to use our reverse method on the list after they're sorted and that would work but there's an easier way to do this instead we can just pass an argument to our sort method called reverse so if I come up here to the sort method and I pass reverse is equal to true and let me also grab this for our number and if I run this you can see that now these sorted are in descending order they're sorted in reverse order now one thing to notice here is that we don't need to reset our variables when we call most of these methods it's just altering the list in place but there's also a way that we can get a sorted version of our list without altering the original list so what if we wanted a sorted version of our courses list without altering the original so to do this we can use the sorted function so instead of calling this sort method on our list well instead use this sorted function and I'll pass courses in two sorted there now if we run this as it is and we can see that our list is not sorted it's exactly how we described it up here now that's because the sorted function doesn't sort the list in place it returns a sorted version of the list so to get that sorted list we have to make a new variable and set it to the return value of the sorted function so I could just call this sorted courses is equal to the sorted version of that courses list and now if we copy that and print that out so now we can see that this sorted courses is equal to the sorted version of that list so that's really useful because a lot of the times you won't want to alter your original list in any way so using this sorted function is a nice way to get a sorted version of that list without altering the original and other than this sorted function there are a couple more useful built-ins that we can use with these sequences so let's look at a few of these so we'll look at min Max and some so it's probably pretty obvious what these will do but if I wanted the minimum value of our numbers list here then let me comment out where we're printing out nums so a built-in function that we can use is just min and call men on our sequence of numbers and if I run that and you can see that it returns one as the minimum number of that list and if we wanted the max value of that list then we could use max and if I run that you can see it returns five now if we wanted to print the sum of that entire sequence that I can just say sum of numbers if I print that then it gets 15 because one plus five plus two plus four plus three is equal to 15 okay so lastly let's see how we can find some values here within our list so let me go ahead and clean up here a little bit and uncomment out that so if we want to define the index of a certain value then we can use the index method for this so if I wanted to find the index of comps I and our list then we could just print out courses dot index and then search for Comp Sci now if we run this and we can see that we got three and three is the index where it found that comps I value now if we try to find the index of a value that doesn't exist in the list and we'll get a value error so if we search that original list of courses for art and run that then we can see that we got a value error and it says art is not in the list now if we just wanted to simply check if the value was in our list and simply get back a true or false result then for this we can use the in operator so if I want to check if art is in our list then I could say art in courses so if I run that and we can see that we got false but if instead we said math in courses and ran that and that returned true now this is going to be especially useful once we go over the topic of conditionals and if-else statements and we're going to go over those in a couple of videos and we can also use this to loop through values of our list by using a for loop so if I was to say for item in courses and then scoot that over then we will just print out that item now this is the first time in our series that we've indented a block of code basically what we're saying here is that we want to create a loop we're looping through each value of our list and each loop through this item variable will be equal to the next item in the list so that's why this line is indented because it tells us that this code is executed from within our for loop so if we run this then we can see that it prints out each item of our list now the reason it prints them all out on a new line is because by default the PERT statement goes to a new line each time it's executed now this item variable is just a variable it's not a keyword or anything we can name this anything we want so instead if we wanted to you know call this course for course and courses and print that out and you can see that we get the same result so we can access each value as we're looping through but sometimes it might be useful to also have the index of what value we're on now to do this in Python we can access the index and the value by using the enumerate function so I will say enumerate and I will wrap courses within that enumerate function and this enumerate function returns two values it returns the index that were on and the value so instead of just getting the course here we're also going to need to get the index so I'll call that index so for index course in the numerator PSA's and now if we print out that index and the course and run that and you can see that we had access to each index and value as we're looping through our list and if we don't want to start at zero then we can pass in a start value to our numerate function so if instead we wanted to start at one and I can pass in the second argument say start is equal to one now if I run this and you can see that now our starting value as one okay so there is one more thing that I want to go over before we move on to tuples and sets so it's pretty common that we'll want to turn our list into strings separated by a certain value now to do this we're actually going to use a string method called join and we're going to pass in our list as the argument so for example let's say that we wanted to turn our list of courses into a string of comma separated values so we can say course string and that will hold the string version of our courses and now we'll type the string that we want to separate each item of our list so I want these to be comma separated so I'll put in a string of a comma and a space and then I'm going to use the join method to join the values of the list using this string so I'll say dot join and I want to join my courses on that string so now if I come down here and print that string version of our courses and run that we can see that we get our values comma separated and if we want to change this then we can just change our string within that we're joining on so if we wanted to hyphenate these then I could just change this to space - space and run that and you can see that when we ran that now we are separating these by the - so this is just one long string with all of our list values joined together now we can also do the reverse of this and turn a string back into a list so we can do this by splitting our string on a certain value so if I split the string that we just created so let me create a new list here and I'll set this equal to the string version of our list and I'll do a dot split and I'll split it on a space - space so if we look at the string version that we have down here this is just one whole string what that saying is it's saying hey split up all of these values on this space comma space and make a list out of all those values that you get so now if we print out our new list so I'll print new list and run that and you can see that now we're back to the original list okay so I know that that was a lot to take in because there's so much that we can do with lists but now let's move on to tuples and sets now that we're familiar with lists then these will probably go pretty quickly okay so tuples are very similar to lists but with one major difference so we can't modify tuples now in programming this is called mutable and immutable so lists are mutable and tuples are not they are immutable so let's look at what this means so I'm going to grab a quick snippet of code here from my snippets file just to compare these so I'm just going to grab from here all the way down to here and just go ahead and paste those in so first we have a regular list here that we've already looked at and we're going to look at one issue that you might run into with mutable objects so what I'm doing here is I'm creating our list of courses and I'm calling this list one and then we're creating another variable here called list two and we're setting that equal to list one and then we're printing out both of these so if I run this then we can see that both list one and list two have the same values so now let me uncomment out this code where we're changing a value in the first index of list 1 and then reprinting our values again so now if I run this then we can see here that all we did was change the value at the first index of list 1 but by changing list ones first value it also changed list two and the reason for that is because they're both the same mutable object now if you need to modify your list then this mutability is what you want but if you want a list of values that you know aren't going to change then we can use a tuple so let's look at a tuple example so I'm going to comment out our mutable example here and then uncomment out our two for example so a tuple looks almost exactly like a list but instead of the square brackets we're using instead using these parentheses and after we create our two we're doing the exact same thing we're calling a creating a variable tuple one that is a tuple and then we're setting this tuple to equal to two point one and for now I'll just comment out where we're changing that first value and I'll run that and you can see that both of these tuples are equal to the same list of values but now if we try to change that value at the first index of tuple one just like we did with our list if we run that then we can see here that we get an error and it says type error tuple does not support item assignment and that's because it's immutable so now since a tuple is immutable it doesn't have nearly as many methods as a list because a lot of those list methods that we looked at involves mutating the values so we can't append we can't remove anything or anything like that but other than that they behave pretty much the same we can loop through tuples we can access values and all the other things that we've already seen except for what mutates the list so that's basically the difference between lists and tuples if you need something that you can modify then use a list but if you just want something that you can loop through and access then you might want to think about a tuple so that you don't run into the issues that we just saw okay and lastly let's look at set now set are values that are unordered and also have no duplicates so let me grab a sample from the snippets file here that we can see so I'm just going to go ahead and grab this small snippet and paste that in so we can see that this looks similar to lists and tuples but instead of the brackets or parentheses we're instead using these curly braces now if I run this code to print this set out and we can see that it prints out of values but if you notice here these aren't in the order that we added them so we had history first here and it has history last down here and if I run this a couple more times and we'll see that you know this order can change with each execution now the reason for this is because unlike our lists or tuples sets don't really care about order because some of them uses for a set is either to test whether a value is part of a set and also it's used a lot to remove duplicate values because sets throw away duplicates so first let's look at how to get rid of duplicates so if I add another math course here to the end of our set and now if I rerun this then we can see that we still only have four courses it got rid of that second math course and it just left us with the one now another thing I mentioned was that it's used to test whether a value is part of a set now this is called a membership test so sets do this a lot more efficiently than lists and tuples so what I mean by this is that within our print statement if I was to say math in CS courses and I run that then when you can see that it prints out true now we could do that with lists and tuples also but sets are optimized for this okay and lastly something else really useful that sets can quickly do is determine what values they either share or don't share with other sets so for example let me create another set called art courses and I'll create this pretty similar to CS courses here but instead of physics and Comp Sci I'll instead say art and design and with both of these I'm going to go ahead and take out that extra math on the end just so it's a little bit more clear and instead of this being CS courses I'm going to call this set art courses so now we have two different sets here and some of them have different courses and some of the courses are the same so let's say that I wanted to see what courses these sets had in common so to do this we could use the intersection method so we can say CS courses dot intersection and we will pass in the art courses into that so if we run that then we can see that it shows us that the history and math courses are in both of those sets and if I wanted to see what courses are in the CS courses but not the art courses then I could use the difference method so instead of intersection we'll instead say difference so if I run that and now we can see that it shows that the physics and Comp side courses weren't in the art courses now if I wanted to combine both of these sets and print all of the courses offered then I could use the Union method so I'll say CS courses dot Union and we want a union with the art courses so if I run that and we can see that now we get all of the courses printed out from both sets so sets can definitely be useful for these kinds of use cases and for these particular problems they're much more performant than lists or tuples okay so we are basically finished up with this video but let me show you one last thing before we close this out and that's going to be how to create empty lists tuples and sets so I have these over here in my snippets so let me grab these real quick and copy and paste these over here and bring this down a line so I wanted to show this because there's a small gotcha when it comes to creating an empty set so to create an empty list we can either set it equal to empty square brackets or we can use this built-in list class and to create an empty tuple we can use these empty parentheses or this built-in tuple class now to create an empty set we actually can't use these empty curly braces so this line right here is wrong that's not an empty set this is actually going to create an empty dictionary so to create an empty set the way to properly do this is to use the built-in set class with no values and speaking of dictionaries that's actually what we're going to cover in our next video but I hope everyone feels comfortable now with working with lists and tuples and sets but if anyone does have any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those now if you enjoy these tutorials and would like to support them and there are several ways you can do that the easiest way is to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching you you
Info
Channel: Corey Schafer
Views: 896,831
Rating: undefined out of 5
Keywords: 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
Id: W8KRzm-HUcc
Channel Id: undefined
Length: 29min 4sec (1744 seconds)
Published: Wed May 17 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.