Lists
Let's say that you wanted to input and store a bunch of numbers. Making individual variables would be a very annoying process. In that case, a list can be used instead. Lists can hold a bunch of values of the same or different type in Python and can be shown with square brackets - listName = []
.
print listName
for example, but you can also print a specific index, for example the second item in the list. This can be done using print listName[(index number)]
. Though you might try listName[2] to access the second index, but you will see that it actually goes out the third item. This is because computers count starting from 0. So instead of the indexes being 1, 2, 3... it is 0, 1, 2...
append
function. To do so you type listName.append(item)
, which adds the new item to the back of the list.
More Details
If you have a list of numbers, you can sort them in both increasing or decreasing order. This can be done using the sort function listName.sort()
.
listName.insert(index, item)
.
"len(listName)"
listName.pop(index)
which removes a specific index mentioned or listName.remove(item)
which removes the item with that value.
Try It Out!
Go to Replit
- Have the user enter words, adding them to a list and print "stop" if "x" is entered. Then print the first and last element in the list.
- Ask the user for three numbers, adding them to a list. Then print the entire list.