2026fa_cse160/lecture20261110/listmethods/list08MethodInsert.py

51 lines
1.6 KiB
Python

#!/usr/bin/python3
# Program: list04
programMessage = '''
This program inserts a value into a list.
'''
print(programMessage)
# Lists of text values
#dogNames = [ "Harry", "Shenanigans","Katrina","Tanner","Yukon Jack", "Colorado","Mandy"]
dogNames = [ "Harry","Katrina","Tanner", "Colorado","Mandy"]
# Print the list and the length
print("Print the length and type of the list.")
print (dogNames," length = ",len(dogNames),"Type =",type(dogNames))
print("\nPrint each element of the list and it's index")
index = 0
for item in dogNames:
print(f"dogNames[{index}] = {item}")
index = index + 1
# Insert a new dog at position 1. Lists begin indexing at 0
newDogName = "Shenanigans"
print("Insert at position 1")
dogNames.insert(1,newDogName)
print(f"The modified list {dogNames}")
print(f"\nInsert a new dog at position 4. Lists begin indexing at 0.")
newDogName = "Yukon Jack"
print("Insert at position 4 after Tanner")
dogNames.insert(4,newDogName)
print(f"The modified list {dogNames}")
print(f"\nLocate a dog name, then insert a new dog after the dog we located.")
message1 ='''
Note: This program is created so the search succeeds.
If the search fails the program will generate an error and stop. This can be
remedied with a try - except block.
'''
print(message1)
searchDog = "Katrina"
newDogName = "Gimli"
print(f"Locate the dog named {searchDog}")
searchDogIndex = dogNames.index(searchDog)
print(f"Found dog {searchDog} at index {searchDogIndex}")
print(f"Insert new dog name = {newDogName} before {searchDog}")
dogNames.insert(searchDogIndex,newDogName)
print(f"The new list = {dogNames}")