Jump to content

For statement with slice copy


Recommended Posts


I'm looking at this piece of code:

words = ['cat', 'window', 'defenestrate']
for w in words[:]:     
    if len(w) > 6:         
        words.insert(0, w)  
words ['defenestrate', 'cat', 'window', 'defenestrate']

If I understand well it should make copy of the list and add 'defenestrate' into list but I receive a message "tuple object has no attribute instert". This code is a part of a tutorial I'm following and not sure why it doesn't work.

Link to comment
Share on other sites

I wasn't referring to the for loop, I was talking about the variable definition.  The error message says you are using a tuple, and like it points out tuples do not have an insert method (you misspelled that in the error message).  If that's true, then it sounds like you've defined the variable using parentheses instead of square brackets, which is why I was asking if that is the actual code you are executing or if you copied and pasted that code from another source.

  • Like 1
Link to comment
Share on other sites

Post the current code you're using, it's tough when you're using something other than what you posted.  I can only debug what I can see.  If that error is on the insert line then it sounds like you're giving it a tuple instead of an integer for the position to insert.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...