Anna
Anna

Reputation: 974

How to replace multiple elements in a list, based on condition?

There is a list

my_name_list = ['Sam', 'Bob', 'John']

I want to replace its values by the position of the value, like this:

my_new_list = ['element_1', 'element_2', 'element_3']

And it's not fixed, can be vary in number of values. From 1 to 7.

I started like so:

for element in my_name_list:
    element = element.replace(element, 'element_' + str(len(my_name_list)))
    my_name_list.append(element)


#But it returns my_new_list = ['element_3', 'element_3', 'element_3']

Upvotes: 1

Views: 307

Answers (1)

DeepSpace
DeepSpace

Reputation: 81594

Your attempt always uses the length of the list as the number:

'element_' + str(len(my_name_list))

This is why all the elements in your output are element_3.

As a matter of fact you don't actually need the original list except for its length.

my_name_list = ['Sam', 'Bob', 'John']
my_new_list = ['element_{}'.format(i) for i in range(1, len(my_name_list) + 1)]
# or
my_new_list = ['element_{}'.format(i + 1) for i in range(len(my_name_list))]
print(my_new_list)

Outputs

['element_1', 'element_2', 'element_3']

Upvotes: 6

Related Questions