0

I have a function that takes a list as parameter (have used a very simple function here to focus on the point of my question).

def some_lst_func(lst):
    foo = len(lst)
    return foo

lst1= [1, 6, 6, 7, 7, 5]

print(some_lst_func(lst1))

For the whole list this works fine, but I want to incrementally pass the list ([1], [1,6].....) to the function and record each output (i.e. increasing length of list).

Below is what I have tried but is clearly not correct, and not sure what the output is that I am getting, what I would expect is

1
2
3...

for num in lst1:
    print(some_lst_func(lst1[:num]))
  • It's not clear why the actual list matters here. Why not just print a range from 1 to the length of the list? At any rate, when you do this `for num in lst1` you are looping over the *values* of the list, not the indexes. – Mark Jun 25 '22 at 23:23
  • In your own words, where the code says `for num in lst1:`, what values do you expect `num` to have each time through the loop? Why? Did you try to **check** what the values are (for example, by putting `print(num)` inside the loop)? What are the values? Do you recognize them? Do you *understand* why this happens? If not, [did you try](https://meta.stackoverflow.com/questions/261592) to find out why, for example [by using a search engine](https://duckduckgo.com/?q=how+does+a+for+loop+work+in+python)? – Karl Knechtel Jun 25 '22 at 23:59
  • @Mark I assume that `len(lst)` in `some_list_func` is a placeholder for actual computation that will be done using various slices of the list. – Karl Knechtel Jun 25 '22 at 23:59

1 Answers1

0

You need to loop over indices, not items:

def some_lst_func(lst):
    return len(lst)

lst1= [1, 6, 6, 7, 7, 5]

for num in range(1, len(lst1) + 1):
    print(some_lst_func(lst1[:num]))

# 1
# 2
# 3
# 4
# 5
# 6

# alternatively, using enumerate:
for num, _ in enumerate(lst1, start=1):
    print(some_lst_func(lst1[:num]))
j1-lee
  • 13,764
  • 3
  • 14
  • 26