Challenge Code: TU12
Points: 15
Prerequisites: Make sure you understand variables and strings
Points: 15
Prerequisites: Make sure you understand variables and strings
You can create a list the same way that you create a variable in Python. The big difference is the type of bracket... [ ] You use the square brackets!
You can create an empty list like this: emptylist = []
To create a list with values you separate each value with a comma. For example:
MyList = [1,2,3,4,5,6]
You can create an empty list like this: emptylist = []
To create a list with values you separate each value with a comma. For example:
MyList = [1,2,3,4,5,6]
Get values
In Python the values start at 0. So look at this list:
MyList = ["Kuala Lumpur","London","Paris","New York","Bangkok"]
You can print the whole list with print(MyList)
To select a part of list you use MyList[0] without any commas.
Try: print(MyList[0]) It will print out Kuala Lumpur. Remember programming languages count from 0 so that's the first item.
You can also select multiple parts of a list using: print(MyList[0:3]) Will print the first 3 cities.
If you don't want the brackets you can use * For example print(*MyList[0:3]) If you would like the comma then you can use a separator in print. print(*MyList[0:3],sep=", ")
You can even start from the right of the list with print(MyList[-1])
EXERCISE 1: Make your own list and print the first to fourth items with commas.
MyList = ["Kuala Lumpur","London","Paris","New York","Bangkok"]
You can print the whole list with print(MyList)
To select a part of list you use MyList[0] without any commas.
Try: print(MyList[0]) It will print out Kuala Lumpur. Remember programming languages count from 0 so that's the first item.
You can also select multiple parts of a list using: print(MyList[0:3]) Will print the first 3 cities.
If you don't want the brackets you can use * For example print(*MyList[0:3]) If you would like the comma then you can use a separator in print. print(*MyList[0:3],sep=", ")
You can even start from the right of the list with print(MyList[-1])
EXERCISE 1: Make your own list and print the first to fourth items with commas.
Appending to your list
To add items to your list
MyList.append("Beijing")
Try printing the list again and you will see it has been added.
MyList.append("Beijing")
Try printing the list again and you will see it has been added.
REMOVING ITEMS from your list
You can remove items from your list using the remove command.
MyList.remove("Kuala Lumpur")
MyList.remove("Kuala Lumpur")
Adding user input to your list
You can use variables and input to add to your list. For example:
NewCity = input("Please add a city ")
MyList.append(NewCity)
print(MyList)
NewCity = input("Please add a city ")
MyList.append(NewCity)
print(MyList)
Sorting your list
You can sort a list with: MyList.sort()
This puts it in alphabetical order.
This puts it in alphabetical order.
EXERCISE 2: Make a list of video game characters that you can input items into.