How to Use Lists in Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this section we're going to look at the built-in data structures in Python which are extremely important when building real applications first we're going to look at lists and then we'll look at tuples sets and dictionaries so earlier you have seen that we can use square brackets to define a list or a sequence of objects in between these brackets we can have objects of any type so we can have a list of strings like this and then assign it to a variable like letters we can also have a list of numbers boolean or even a list of lists let me show you so here we have a list each item in this list will be a list itself so here's the first item which is a list of two items now let's add another item to our main or parent list this item is also a list with two items so now we have a matrix which is a two dimensional list now let me show you some cool tricks let's say you want to have a list of a hundred zeros you don't want to manually create that like this that's very ugly let me show you a better way so we define a list of one item on 0 and then we can multiply it by 100 and the result will be this let me show you friend zeros here it is there you go so using a star or an asterisk we can repeat the items in a list now similarly we can use a plus to concatenate multiple lists let me show you so first I'm gonna change this to 5 now let's define a variable combined which is our zeros list plus letters let's see what happens print combined you know it so we have 5 zeros followed by ABC as you can see in Python every object in a list can be of a different type so they don't have to be exactly the same type we can combine a list of numbers with strings and boolean or even lists now let's say you want to have a list of numbers like 0 1 2 3 all the way up to 20 you don't want to type all of these by hand there is a better way so we have this list function as you can see this function takes an iterable so we can pass any iterable here and convert it to a list earlier you learn about the range function this function returns a range object which is iterable which means we can iterate or loop over it so here we can call this function and pass 20 and with this we can create a list of numbers from 0 to 20 let me show you so let's store it in numbers and then print it on the terminal there you go so 0 up to 20 but note that 20 itself is not included as another example let's call the list function and pass a string earlier I told you that strings are also a turrible we can loop over them so we can pass them to the list function and see what we get let's print chars on the terminal so you can see each character in our original string is an item in this list so these are a few different ways to create a list in Python now that we have a list we can get the number of items in that list using the Len function so here we can print the Len or length of chars let's take a look so we have 11 items in this list over the next few lectures we'll look at various operations around lists so here we have a list of four items we can use square brackets to access individual items in this list so let's print letters of zero this will return the first item in this list so when we run this program we'll get a now similar to strings if we pass a negative index here like negative one this will return the first item from the end of the list so when you run this we'll get D using square brackets we can also modify items in the list so let's change the first item to a capital A and then print the entire list there you go so this is the basic of accessing individual elements in the list the earlier in the course you learn that we can use two indexes to slice a string we have the exact same concept here so we add square brackets first index colon second index and this will return a new list with the first three items in our original list so if we print our original list you can see that it's not changed now just like strings if you don't specify the first argument 0 will be assumed by default so as you can see these two expressions produce the exact same result similarly if you don't include the end index by default the lengths of the list will be used here so this expression will return a new list with all the items in the original list and similarly we can also exclude the start index here and with this syntax we can get a copy of our original list there you go now when slicing a string we can also pass a step and this is useful in situations where you want to return every second or every third element in the original list so now when we run this code we'll get a and C so B will be a skipped let me show you using a better example so I'm going to delete everything here create a new list called numbers here we're gonna use the list function and pass range of 20 let's print our list so we get numbers 0 to 19 okay now let's see what happens when we add square brackets here with two colons and two this will return every other element in the original list take a look so we get all the even numbers 0 2 4 and so on it's pretty cool isn't it here's another cool thing you can do here let's change the step to negative 1 as you can see this will return all the items in the original list but in reverse order so these are some useful things you can do with lists next we'll look at unpacking lists there are times that you may want to get individual items in a list and assign them to different variables here is an example we can define a variable like first and set it to numbers of zero similarly we can define second set it to numbers of one and third set it to numbers of two perhaps we are going to use these variables in a few complex expressions in your code now there is a cleaner and more elegant way to achieve the same result and that is what we call list unpacking so we can unpack this list into multiple variables let me show you how that works so we define our variables like first second and third and then set them to our list what we have on line two is exactly identical to what we have on lines four to six this is what we call list unpacking now what is important here is that the number of variables that we have on the left side of the assignment operator should be equal to the number of items we have in the list so if we exclude third here and run this program we will get an error value error too many values to unpack so there are too many items in this list and we cannot unpack it into enough variables now what if in this list we have so many items but we only care about the first two we don't want to define so many variables on the left side of the assignment operator well we can get the first and second and then pack the rest inside of a separate list called other with this syntax we'll get the first and second items and everything else will be stored in a separate list called other let me show you so let's print first and let's also print other now we don't need these few lines here let's run this code so first is one and other is a list of all the items after the second item that is the list I'm talking about so in this example we have both unpacking and packing first we try to unpack this numbers list into the variables on the left side of the assignment operator and then because we have used an asterisk here we're basically packing all the other items into a separate list now to refresh your memory earlier we use this syntax when defining a function with a variable number of arguments remember we had a function like this multiplied with a parameter called asterisk numbers and then we could call this multiplied with arbitrary number of arguments so when we prefix a parameter with an asterisk Python will get all these arbitrary arguments and pack them into a list this is exactly what is happening on line two now let me delete this other stuff now let's change this example a little bit what if we care only about the first and the last item well we can put other in between so we get the first other and then the last item so let's change the last item to nine and then print first last and other this is what we get so first there's one last is nine and the rest is here so this is all about list unpacking in this lecture I'm gonna show you how to loop over lists so here we have a list of three items we can use our four loops to loop over this list so for letter in letters : and then we print each letter save the changes and run the code we get ABC now what if you want to get the index of each item as well well we have a built-in function called enumerate we call it here and this will return an enumerator object which is iterable in each iteration this enumerate object will give us a tapa let me show you so now when we run this code look in each iteration we're getting a topple so a topple as I told you before is like your list but it's read-only we cannot add new items to it so in each iteration we're getting a topple of two items the first item in this topple is the index and the second item is the item at that index so now to get the index we can use square brackets to access the first item in this topple so if we print letter of 0 we will get the indexes and right next to that we can add letter a 1 so we will see the item at a given index but this syntax is a little bit ugly in the last lecture you'll learn about list unpacking so if we have a list with two items 0 and a we can unpack it into two variables like this index comma letter equals items so here we are unpacking the items list now what if we change square brackets to parentheses now we have a table all and we can still unpack this topple so you saw that this enumerate function returns an enumerate object which is iterable in each iteration this enumerate object will return a tuple that looks like this so we can unpack kid right here so we add another variable index now with this we no longer have to use square brackets and we can simply print index and letter let's run this code there you go so now we don't need this anymore so to recap you can use four loops to iterate over lists if you also need the index you should call the enumerate function this will return an enumerate object which is iterable in each iteration it will return a tuple and you can unpack that topple right here in this lecture I'm going to show you how to add new items to a list or remove existing items so for adding items you have two options depending on where you want to add this new item if you want to add an item at the end of the list you should use the append method so earlier you learned that everything in Python is an object so we can use the dot notation to access individual functions or more accurately methods in that object so when a function is part of an object we refer to that function as a method so here are all the methods available on list objects we use the append method to add something at the end of this list let's print our letters and we will get ABCD beautiful now if you want to add an item at a specific position you should use the insert method so letters that insert we can add something at the beginning of the list so index 0 let's add a hyphen and then print the result so this is what we get now for removing objects again you have a few different options if you want to remove the item at the end of the list you should use the pop method so here recall letters dot pop this will remove the letter D at the end of our list so now let's print our letters as you can see D is gone we can also pass on index here to remove the item at the given index so if you pass 0 instead of D this - will be removed let's take a look we run this so the hyphen is gone and we get ABCD beautiful now there are times that you want to remove an object but you don't know its index if that's the case we can use the remove method so letters that remove here we can remove B and this will remove the first occurrence of the letter B so if you have multiple B's only the first one will be removed if you want to remove all B's in this list you'll have to loop over this list and we of each be individually now let's run this code one more time so you can see B is gone we have another way to remove an item from a list and that is using the Dell or delete statement so here we can delete an item by its index we can also delete a range of items so this is the difference between the delete statement and the pop method the pop method will remove only one item by index whereas with the delete statement we can remove a range of items and finally if you want to remove all the objects in the list you should use the clear method next we'll look at finding objects in a list there are times that you want to find the index of a given object in a list so let's say we want to find the index of letter A in our letters list we call letters dot index and pass a let's print the result so this will return 0 what if you try to get the index of an object that doesn't exist here like D we get a value error D is not in the list this behavior is different from a lot of programming languages out there C based languages return negative 1 if you try to get the index of an object that doesn't exist in the list but in Python we get an error so to prevent this error from happening first you should check to see if the given object exists in the list and for that we use the in operator so if D is in letters then we will print its index so now we run the program and we don't get any errors we also have another method that you might find useful in certain situations and that is count so letters that count this will return the number of occurrences of the given item in this list so when we print the result we'll get 0 hi guys thank you for watching this tutorial my name is Mohamad ani and I have tons of tutorials like this for you on my channel so be sure to subscribe and also please like and share this video if you want to learn Python properly from scratch with depth I have a comprehensive python tutorial for you the link is below this video so click the link to get started thank you and have a fantastic day
Info
Channel: Programming with Mosh
Views: 58,856
Rating: 4.9430008 out of 5
Keywords: python lists, python list tutorial, list in python, python sort list, python list, lists in python, python tutorial for beginners, python for beginners, python basics, absolute beginners, learn python, code with mosh, python tutorial, python (programming language), python for absolute beginners, getting started with python, python list methods, learn python online, python tutorials for beginners, python 3 tutorial, python, python programming
Id: 9OeznAkyQz4
Channel Id: undefined
Length: 18min 48sec (1128 seconds)
Published: Thu Nov 08 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.