Jump to content
Truman

For statement with slice copy

Recommended Posts

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.

Share this post


Link to post
Share on other sites

Are you sure that's the exact code you're using?  The error message says you've defined a tuple instead of a list.

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

You will find the last part is not part of code, but what will be the result when the code is run and finishes.

replace last line with:

print words

 

 

  • Thanks 1

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
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

×