Let's say I have a list with the following values:
values=['foo','bar','lorem','ipsum']
I want that for every element of the list, iterates the entire list adding up the length of the current item + all the other lengths. This is done by a function that does the following:
def sum_length(first_string,second_string):
return len(first_string)+len(second_string)
My code looks like this
for i,_ in enumerate(values):
counter=i
while counter < len(values):
print(sum_length(values[i],values[counter]))
counter+=1
So the first iteration would be
1. len('foo') + len('bar')
2. len('foo') + len('lorem')
3. len('foo') + len('ipsum')
Second:
1. len('bar') + len('lorem')
2. len('bar') + len('ipsum')
This is not very effective with very big lists or more complex functions, how could I improve my running time?
source https://stackoverflow.com/questions/71591641/iterating-a-list-to-apply-a-function-to-each-element-from-current-position
Comments
Post a Comment