Home > OS >  Appending "Sir" to list of names? PYTHON
Appending "Sir" to list of names? PYTHON

Time:11-20

I already did the first half my task but am struggling with the second:

"Create a second empty array called sir_beatles. Write the pseudocode and python code to copy the contents of the beatles array into the sir_beatles array, and append Sir at the beginning of each name, so the new array contains Sir John, Sir Paul, Sir Ringo, Sir George."

My code

size = 4
index = 0
beatles = ["John", "Paul", "Ringo", "George"]

for index in range(len(beatles)):
    print(beatles[index])

sir_beatles = [None] * size

for index in range(0, size):
    sir_beatles[index] = beatles[index]
    print(sir_beatles[index])

So it's printing both lists but I am at a total loss with how to add Sir to each index. I tried

sir_beatles[index].append("Sir")

but I get the error code AttributeError: 'str' object has no attribute 'append' I tried .insert() as well and have the same error.

Any suggestions?

CodePudding user response:

You can use list comprehension with f-string:

beatles = ["John", "Paul", "Ringo", "George"]
sir_beatles = [f"Sir {member}" for member in beatles]

print(sir_beatles) # ['Sir John', 'Sir Paul', 'Sir Ringo', 'Sir George']

If, for some reason, you want an explicit for loop, then

sir_beatles = []
for member in beatles:
    sir_beatles.append(f"Sir {member}")

is an equivalent implementation.

  • Related