-4

I actially goten the code from the techer. I am not gettign output. What is error. It is out of index. I dont understand pls help.

   def something(tu):
      ch='a'
      for i in tu:
         tu[i]=ch
         ch+='a'
   l=[1,4,2,3,8]
   something(l)
   for i in l:
       print(i)
   print("The end!")

The expted output is

    a
    aa
    aaa
    aaaa
    aaaaa
    The end!

Thank you

deepakchethan
  • 5,240
  • 1
  • 23
  • 33

1 Answers1

0

You need to make changes to the python code, here is the changed one:

def something(tu):
   ch='a'
   for i in range(len(tu)):
      tu[i]=ch
      ch+='a'
l=[1,4,2,3,8]
something(l)
for i in l:
    print(i)
print("The end!")

The reason you may get error is, you have an 8 in your list. But the max length of the list is only 5. So change the i in that. Alternatively change the 8 to 0. It will work too. The index is out of bounds. I changed the indentation too.

deepakchethan
  • 5,240
  • 1
  • 23
  • 33
  • You could highlight that `for i in tu` iterates over the elements themselves, while `for i in range(len(tu))` iterates over the *index*. Normally you would use `for index, element in tu` instead, since it is considered more pythonic. See [this answer](https://stackoverflow.com/a/522578/6725184) for more details. – Christian König Jun 14 '17 at 08:31