In this post, we're going to talk about how to store and manipulate values in a Python list. Understanding all the ways you can store and use values is integral to mastering any coding language, and Python is no exception. For the purposes of this post, let's use the following list as an example:

l = [1, 2, 3, 4]

So the list above is called l, and it contains four values, 1, 2, 3, and 4. That much should be pretty self explanatory. What we're going to do next is learn how to quickly and easily store each value in that list as separate values in your Python code.

Let's say that you'd like to save values 1, 2, 3, and 4 as variables a, b, c, and d, respectively. There are a number of different ways to do this, including iterating through the list, or manually going through the list using indices that correspond to each value, but the quickest way to achieve this is by doing the following simple step:

l = [1, 2, 3, 4]
a, b, c, d = l

That's literally all you need to do. Now the value for the variable a will be 1, b will be 2, c will be 3, and d will be 4.

You can do this using as many values as you like...when you run out of letters of the alphabet, start combining them to makes words and store the variables as words rather than letters. Just remember that the order of the items in the list is the order that they will save to the variables, so be sure to write them in the correct order (for example, if in the code snippet above you wanted the value 3 to be saved as d instead of c, just place d in the third position and whatever you like in the fourth...perhaps c?).

Could it be any simpler or easier than this? Probably not. This is a great trick to keep in your back pocket.



To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.