0

I have defined a class and want to add an instance to a list. How do I do that? I have tried...

class MyClass:
    var1=''
    var2=''

thelist = []
instance = MyClass()
instance.var1 = "hello"
instance.var2 = "world"
thelist.extend(instance)

and I am getting a

TypeError: iteration over non-sequence

1 Answer 1

3

You want list.append(), not list.extend():

thelist.append(instance)

list.extend() expects a sequence of elements to add, adding them all to the list. You have just one element, in which case you need to use list.append().

From More on Lists in the Python tutorial:

list.append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

Emphasis mine.

Demo:

>>> class MyClass:
...     var1=''
...     var2=''
... 
>>> thelist = []
>>> instance = MyClass()
>>> instance.var1 = "hello"
>>> instance.var2 = "world"
>>> thelist.append(instance)
>>> thelist
[<__main__.MyClass instance at 0x106d19d40>]
>>> thelist[0].var1
'hello'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.