Introduction to Python Module Four Part Two: Indexing
Now that you are acquainted with lists, it is time to learn a little bit more about them. Today’s post is about indexing. You are going to learn more about how indexes work in lists and how to use them in code. Indexing is a lot more than calling parts of a list you might need. Developers use indexing to double-check what value is at a specific index. This makes it very helpful when debugging lists. Lists are mutable. Mutable means that any values inside a list can be changed after it has been made. At Coding with Kids, the values in the lists the students created throughout their projects would constantly change with certain values being added, removed, or changed. How to Change a Value in a List To change a value in a list, use the list name followed by the square brackets. Inside the square brackets put the number of the index you want to change. After the closing square bracket, put the equal sign followed by the value you are changing. In the example below, I have a list called grocery_cart. When I want to replace the second value in the list, I use the index value of 1 because I’m counting the way the computer counts. I print this index value to the console to doble-check what value is at this index to see if things have changed. grocery_cart = [ " chicken " , " ground beef " , " salad mix " , " blueberries " , " tuna " ] grocery_cart [ 1 ] = " cheese " print ( grocery_cart [ 1 ]) # print cheese If you have a bunch of variables in your code, you can move information stored in variables and put them inside a list. In the example below, I have different variables with various values assigned to them. name = " Lucky " age = 15 color = " orange " If I want to turn these variables into a list, , I can create a new variable called cat. After the equal sign, I will assigned the values as list items inside the square brackets. cat = [ " Lucky " , 15 , " orange " ] Indexing with Strings Developers use indexing to select specific characters in a string. Strings are simi