A list can hold collections of strings, integers or floats to use in your program.
You can combine it with random to choose a random item from your list.
Creating a list
rucksack = ["gold coin","rope","cheese roll"]
print(rucksack[0])
print(rucksack[2])
print(rucksack)
#Create a list inside variable rucksack
#Print first item in the list
#Print third item in list
#print whole list
This would output as
Note 0 refers to the first item in the list, 1 to the second item etc
You can create an empty list and add things later on in the program.
rucksack = [ ]
Adding items to the end of a list
rucksack = ["gold coin","rope","cheese roll"] #This creates a list called rucksack
rucksack.append("sword") #This adds the sword onto the list rucksack
print(rucksack) #Print rucksack list
This would output as
twotimes = [2,4,6,8] #Create a list called twotimes
twotimes.append(10) #This adds the 10 to the end of the twotimes list
print(twotimes) #Print list called twotimes
This would output as
>>>
[2, 4, 6, 8, 10]
>>>
This would output as
Insert item into a specific place in the list
rucksack = ["gold coin","rope","cheese roll"]
rucksack.insert(2,"fried fish") #This will insert fried fish at position 2 in the list
print(rucksack)
This would output as
Note 2 is actually third place in the list as first is position 0
This would output as
Deleting items from a list
rucksack = ["gold coin","rope","cheese roll"]
rucksack.remove("rope") #Removes rope from list
print(rucksack)
This would output as
This would output as
Removing an item and using that removed item (pop)
This would output as
Using Count to find out how many times an item occurs in the list (count)
This would output as
Using index to find where in a list something is (index)
This would output as
Using list sort to re-order a list (sort)
This would output as
Revering the list order using reverse (reverse)
Extending the list (extend)
This would output as
Checking to see if something is in a list
rucksack = ["gold coin","rope","cheese roll"]
if "cheese roll" in rucksack:
print("You have a cheese roll")
else:
print("You don't have a cheese roll")
This would output as
You can also use not in such as
if "cheese roll" not in rucksack:
To find out more about if else
Combining two lists
playerrucksack = ["gold coin","rope","cheese roll"]
chest1 = ["ruby","emerald","Wand of Doom"]
playerrucksack = playerrucksack +chest1
print(playerrucksack)
You can combine two lists
This would output as
Looping through items in a list
You can find out how to do this using a for loop.