Skip to main content

List

List is an ordered collection of items.

You could make a list for a shopping cart, or a list of friends.

list = [1, 2, 3, 4, 5]

List Declaration

List is declared with square brackets [].

list = [1, 2, 3, 4, 5]

There are commas between each item in the list.

List Indexing

Similar to strings, you can find the value of an item in a list using the index.

list = [1, 2, 3, 4, 5]
print(list[0])
print(list[1])

Note that the index starts at 0.

Change values using indexing

You can replace an item existing in a list using the index.

list = [1, 2, 3, 4, 5]
list[0] = 0
print(list)

You can also replace a range of items in a list.

list = [1, 2, 3, 4, 5]
list[0:2] = [0, 0]
print(list)

Note that this can also be done in strings, too.