- FOR and WHILE loops are essential to make full use of lists with the minimum amount of code
- The len() function can tell you how big your list is
- The in operator will be your best friend soon. It makes life very easy
#List containing 4 names + print (good for testing)
names = ["Joe","Mike","Sarah","Charlie"]
print(names)
#Get length and print
length = len(names)
print(length)
#Using the 'in' operator to cycle through each name and print.
#The IF statement checks for "Joe", and finds the position in the list
for name in names:
print(name)
if name == "Joe":
print("Hey Joe, love Jimi!")
position = names.index("Joe")
print("Found at index: " + str(position))
Tasks
- Type in the code and make sure that it works
- Modify the program to allow the user to input a name to search for
- Modify to use a list of 10 names, and print custom messages for two other names
- Save and label your code
Extension Task
The index number is frequently used to identify the exact position of an item in the list, usually so you can delete it using the code below, the position variable containing the index of the item to remove. Modify the program to ask if the name should be deleted if it is found in the list
names.pop(position)