List

Topic

List

Topic Progress:

A list in python allows us to store a collection of items. The list below describes the different properties of a list

  • A collection of items stored together in a single variable
  • Each item is kept in a specific order
  • Items within the list can be changed
  • Duplicate items can be stored in the list

To create a new list we first need a variable and then to set it to the items inside of square brackets [] with a comma in between each item as shown below

exampleList = ["hello","welcome","to","codecamp"]

If we want to print all of the items in the list we can do so by using a print command with the list name inside the brackets like this

print(exampleList)

When we run this command it will output this:

['hello', 'welcome', 'to', 'codecamp']

Try making a list with your 3 favorite hobbies and then print it in the repl.it section below


We can also access certain places within the list known as an index. While it may seem confusing the first index of our list always starts at 0 and goes up to the last index of the list. For example if we wanted the first item we write and to print it out we can put it in a print like we did above

exampleList[0]

Using what you have just learned in the code section below get it to print the word codecamp


As mentioned at the top we can change the values within our list. To do this we need to tell the code which index we want to change and then set that value as demonstrated below

exampleList[0] = "hi"

Try change the list below so instead of having codecamp as the last item it now says your name


Using a for loop we can also go through each item of a list. The code below will print out each item in the list

As you can see when you run the code it prints out each item rather than printing the whole array. If we want to change the current item instead of print we can write item = {newItem} . Where instead of {newItem} we would write the item we want to replace it with.

Using the repl.it below try and change the code so that it changes all the items in the array to your name

@

Not recently active