-1

for i in l, gives an error:

l=["Mohi", "Moki", "Lucky", "Praty", "Prem"]
k=[]
for i in l:
   k.append(l[i])
print(k) 

but no error when I do this:

l=["Mohi", "Moki", "Lucky", "Praty", "Prem"]
k=[]
for i in range(len(l)):
   k.append(l[i])
print(k)

Blockquote

  • 2
    `for i in l` gives you `"Mohi"`, `"Moki"`, etc., **not** `0`, `1`, etc. You are effectively doing `l["Mohi"]` which doesn't make sense for lists. – matszwecja Sep 29 '22 at 09:15
  • 1
    Because with your first code i is list actual list value like 'Mohi', unlike in secode code i represts the elements' index value such as 1,2,3. I suggests to print i in both loop and compare. – R. Baraiya Sep 29 '22 at 09:16
  • 1
    Try `k.append(l)` or just skip the loop and do `k = l[:]` (which makes a shallow copy of the list). A good debugging step (if you can't attach a debugger) would have been to print out the value of `l` during the loop, which would have immediately shown you the problem. – Kemp Sep 29 '22 at 09:16
  • 1
    @Kemp, `k.append(l)` will append single element - the `l` list itself. They should use `k.extend(l)` or inside the loop `k.append(i)`. `k = l[:]` on other hand will replace the current `k` list with copy of `l` - again not what OP wants. – buran Sep 29 '22 at 09:23
  • 1
    Does this answer your question? [TypeError/IndexError when iterating with a for loop, and referencing lst\[i\]](https://stackoverflow.com/questions/52890793/typeerror-indexerror-when-iterating-with-a-for-loop-and-referencing-lsti) – buran Sep 29 '22 at 09:26
  • Also [Why do I get an IndexError (or TypeError, or just wrong results) from "ar[i]" inside "for i in ar"?](https://stackoverflow.com/q/51919448/4046632) and [How does a Python for loop with iterable work?](https://stackoverflow.com/q/1292189/4046632) – buran Sep 29 '22 at 09:27
  • 1
    @buran I meant `i` rather than `l`, a little typo. Past the edit grace period now though :) I figured replacing `k` would be fine as they define it as an empty list here anyway. Caveats apply. – Kemp Sep 29 '22 at 09:29

1 Answers1

1

i is the element from the list, it's not an index.

name
  • 11
  • 1