Jump to content

Recommended Posts

Posted

Hi,

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.

Posted

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
Posted

You're correct but after changing it to square brackets I receive TypeError: list indices must be integer or slices, not tuple.

Posted

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.

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

this is my code.

Posted (edited)

OR

words = ['book', 'superficial', 'nostradamus']
for w in words:
    print(w, len(w))
for w in words[:]:
     if len(w) > 6:
         words.insert(0, w)

print ('words'+ str(words))

It will print a string representation of words array and its values.

Edited by dsonesuk
  • Like 1

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...