Reputation: 51
I have a list of strings and would like to use a for loop to change the strings and create a new list.
oldList = ['AAA','BBB','CCC']
for i in range(len(oldList)):
newList = []
add1 = 'a_'
add2 = '_z'
newStr = add1 + oldList[i] + add2
newList.append(newStr)
The list 'newList' should contain all the strings on the old list plus the amendments (i.e. ['a_AAA_z', 'a_BBB_z', 'a_CCC_z']). However, it only contains the last string (i.e. ['a_CCC_z']).
What am I missig here? Many thanks in advance.
Upvotes: 0
Views: 1237
Reputation: 236004
Declare the output list outside of the loop. It can be simplified, by the way:
newList = []
for ele in oldList:
add1 = 'a_'
add2 = '_z'
newStr = add1 + ele + add2
newList.append(newStr)
Or we can simplify even further if we use a list comprehension and formatted strings, as suggested by @AnnZen
newList = [f"a_{ele}_z" for ele in oldList]
Upvotes: 4
Reputation: 27567
You can use formatted strings and list comprehensions:
oldList = ['AAA','BBB','CCC']
newList = [f'a_{s}_z' for s in oldList]
print(newList)
Output:
['a_AAA_z', 'a_BBB_z', 'a_CCC_z']
Upvotes: 1
Reputation: 71
You need to initialize the newList
outside the for loop otherwise it will get initialized at every iteration.
This code snippet might help.
oldList = ['AAA','BBB','CCC']
newList = []
for i in range(len(oldList)):
add1 = 'a_'
add2 = '_z'
newStr = add1 + oldList[i] + add2
newList.append(newStr)
print(newList)
Upvotes: 0
Reputation: 2502
You need to declare newList
outside the for-loop. If you declare it inside the for-loop, then on each iteration of the for-loop you're reassigning the variable newList
to be equal to an empty list, and hence you lose your data from the previous iterations (leaving you with only the data from the last iteration.
Here's your code with the declaration fixed:
oldList = ['AAA','BBB','CCC']
newList = []
for i in range(len(oldList)):
add1 = 'a_'
add2 = '_z'
newStr = add1 + oldList[i] + add2
newList.append(newStr)
and here's an even simplified version:
oldList = ['AAA','BBB','CCC']
newList = ['a_' + str + '_z' for str in oldList]
Upvotes: 0
Reputation: 2882
Use list comp:
oldList = ['AAA','BBB','CCC']
newList = ['a_' + i + '_z' for i in oldList]
Upvotes: 0
Reputation: 879
The declaration of list should be outside the loop
oldList = ['AAA','BBB','CCC']
newList = []
for i in range(len(oldList)):
# should not declare newList inside for loop
#newList = []
add1 = 'a_'
add2 = '_z'
newStr = add1 + oldList[i] + add2
newList.append(newStr)
print(newList)
Upvotes: 1