DEV Community

Sarah Bartley
Sarah Bartley

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

Indexing with Strings

Developers use indexing to select specific characters in a string. Strings are similar to lists because they are sequences of items or characters. As you use indexing with strings, keep in mind that strings are a sequence of characters, so that includes punctuation and spaces along with individual letters.

For example, the code below has a variable called name with my name assigned as the value. My name is a string so I can use indexing to select characters in the string.

name = "Sarah"
print(name[1]) # print a
print(name[3]) # print a
Enter fullscreen mode Exit fullscreen mode

Lists may be mutable, but strings aren’t. When developers are working with code that is immutable, they can’t change any of the characters in a string. If you try changing a character in a string, you will get an error message.

Top comments (0)