Added code for lecture 2026-11-10
This commit is contained in:
parent
5b630435ae
commit
07b9e54bf0
52 changed files with 1248 additions and 1 deletions
51
lecture20261110/listmethods/list08MethodInsert.py
Normal file
51
lecture20261110/listmethods/list08MethodInsert.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
#!/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}")
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue