Python - Intro to Lists

04.12.2020

An example

Lists are one of the most fundamental types in python (or an programming language). They are simply a collection of data; a list of data :P. Let's start with a quick example:

myList = [1, "something", 3.0]

Notice that in python, the data inside a list does not have to be of the same type.

Accessing Elements in a List

Now that we have a list, let's try to get the data the list is holding.

print(myList[0]) # prints 1
print(myList[1]) # prints "something"
print(myList[2]) # prints 3.0

We can access the list values by adding brackets [] and the index of the object we would like the value of. Note that in the first item is of index 0, not 1. This something to always remember when programming.

Adding and Removing Items to a list

We defined a list, but let's say we want to add more info to our list. We can do this by using the append method.

myList.append("newValue")

print(myList) # [1, "something", 3.0, "newValue"]

We can also remove elements using the del keyword.

del myList[1]

print(myList) # [1, 3.0, "newValue"]

Looping over a list

Let's end with an example of how to loop over a list. If you have read about loops yet, don't worry, the syntax is easy to follow. Looping over a list is one of the most common things you will do in programming.

for item in myList:
    print(item)

It's pretty simple! We are just saying, "for each item in myList, print the item." You will be using this a lot in your programming adventures.

That's all for now. There is much more to learn about lists, so we will return to them often.

References