Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate through a list using index

I am making a function that counts from 0 to a certain number input I tried to make it using print and that worked but the output needs to be a return value so I tried making a list then iterating through it using a for loop and returning each value of the list back using the index of the list but that didn’t work it only returns the last value of the list I also want the returned value to be a string, not a list.

this is my code

nums = []
def numbers_range(number):
  for i in range(number+1):
    numz = nums.append(i)
  for g in range(len(nums)):
   numb = nums[g]
  return numb

print(numbers_range(5))

result 5
the result i want 0 1 2 3 4 5
please help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

one solution is

def numbers_range(number):
  for i in range(number+1):
    yield i;


result = numbers_range(5)
for i in result:
    print(i,end=" ")

another solution is

def numbers_range(number):
    ans = []
    for i in range(number+1):
        ans.append(i)
    return ans
    


result = numbers_range(5)
for i in result:
    print(i,end=" ")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading