What is a list?
A list is used to group certain information together. They are ordered, and the information in them can be changed.
Creating a List
To create a list in python, simply add information in between [] and put commas between each value.
rainbow_colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
Indexing and Accessing Values
Like we said earlier, lists are ordered. So, whatever order you put something into the list remains throughout the program.
Each value added to the list is given an index. The first value has index 0. Every subsequent value has an index of 1, 2, 3, etc. To access a particular value in a list, type the list’s name, followed by square brackets and the index of the value you want to access.
rainbow_colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
color = rainbow_colors[3]
print(color)
OUTPUT
green
It will take some getting used to, but typically, in programming languages, all indices start from 0, not 1.
In addition to accessing via index, you can also slice a part of a list out using an initial and final index in the form list_name[initial:final].
rainbow_colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
colors = rainbow_colors[0:3]
print(colors)
OUTPUT
["violet","indigo","blue"]
Here, a part of the list is sliced and assigned to a new variable "colors" and it is printed out to the console.
Using For Loops
We can also use for loops to access and work with each value in a list. To write a for loop, use the following format…
for item_name in list_name:
#code to run with each item_name
Here, list_name is replaced by the name of your list, and item_name should be replaced by any descriptive name you can think of to call each item in the list. You can then use that descriptive name as a variable inside the for loop to work with that value. For example…
rainbow_colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
for color in rainbow_colors:
print(color)
OUTPUT
violet
blue
indigo
blue
green
yellow
orange
red
Here, we gave a random name to each item in the list, color and then used it like a variable, inside the for loop. So, each item in the rainbow_colors list is printed on a new line.
String Indexing and Slicing
Just like you index lists, you can also index a string to access a certain character or group of characters.
To do so, just take the variable the string is assigned to, and access an index of it, like a list.
You can also set a range of characters using [starting index:finishing index].
test_string = "I am happy today"
feeling = test_string[5:10]
person = test_string[0]
print("Feeling: " + feeling)
print("Person: " + person)
OUTPUT
Feeling: happy
Person: I
Here, the word "happy" is sliced from the string test_string by slicing it like a list. The letter "I" is taken from the string test_string by accessing it using a list index.