Reputation: 521
I have a list of strings and I hope to add an additional space to the latter element in it.
my_list = ['AA',
'BB',
'CC',
'DD']
my expected outputs:
my_list = ['AA',
' BB',
' CC',
' DD']
I only know how to add space to each element using the code below:
[' '+i for i in my_list[1:]]
Any suggestion is much appreciated!
Thank you.
Upvotes: 1
Views: 37
Reputation: 4241
The simple approach is using a for loop:
my_list = ['AA',
'BB',
'CC',
'DD']
for i in range(0,len(my_list)):
my_list[i]= " " * i + my_list[i]
print(my_list)
Upvotes: 1
Reputation: 2167
Your can get the expected result with list_comprehension and enumerate()
:
my_list = ['AA', 'BB', 'CC', 'DD']
new_list = [" "*i + el for i, el in enumerate(my_list)]
# > ['AA', ' BB', ' CC', ' DD']
Upvotes: 4