praxmon
praxmon

Reputation: 5131

Python: append() function not working

This is the code I have written:

import sys
import string

def reverse(li):
    li=li[::-1]
    return li

a=raw_input("Enter first line ")
c=[]
c=a[0:2]
a=reverse(a)
b=[]
i=0
for i in range(0, len(a)):
    if(a[i]==' '):
        b=a[:i]
        b=reverse(b)
b.append(c) 
print b

Here the error is: 'str' object has no attribute 'append' on line b.append(c).

Why is this error creeping up? Where am I going wrong?

Upvotes: 0

Views: 2732

Answers (3)

Vineeth Guna
Vineeth Guna

Reputation: 398

In python str object does not have an append() method but list object has append() method

In your code b = [] Initially you defined b as a list

b=reverse(b) But this statement in your code will convert b from list to str

As str object i.e b does not have an append() you will get an error

Upvotes: 0

user2555451
user2555451

Reputation:

It's because you make b a string with this line:

b=str(reverse(b))

Doing so overshadows the list. Pick a different variable name to solve your problem.

Also, there is no need to make a function reverse because Python has a built-in reversed function:

>>> a = [1, 2, 3]
>>> reversed(a)
<listreverseiterator object at 0x015AC6B0>
>>> list(reversed(a))
[3, 2, 1]
>>>

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122526

You are turning b into a string in the line above it:

b=str(reverse(b))

Hence, b is now a string and it won't support the .append() method which is for lists.

Upvotes: 1

Related Questions