BeeFriedman
BeeFriedman

Reputation: 1974

Why am i getting this error when i am trying to insert a string into a list?

i am running the following code.

a = ["hello","bye","where","am","i"]
ls_capitalize = [x.capitalize() for x in a]
reverse = reversed(ls_capitalize)
reverse.insert(2,"Extra")
print(reverse,"\n",ls_capitalize )

I am trying to insert a string in the list after reversing it and i am getting the following error.

Traceback (most recent call last):
  File "<input>", line 4, in <module>
AttributeError: 'list_reverseiterator' object has no attribute 'insert'

If insert() is not working for this what could i use?

Upvotes: 0

Views: 720

Answers (1)

saquintes
saquintes

Reputation: 1089

The problem is reversed doesn't return a list, it returns an iterator. That's why it says list_reverseiterator doesn't have insert. Try

a = ["hello","bye","where","am","i"]
ls_capitalize = [x.capitalize() for x in a]
reverse = list(reversed(ls_capitalize))
reverse.insert(2,"Extra")
print(reverse,"\n",ls_capitalize )

Upvotes: 3

Related Questions