0
class Hat:
    def __init__(self, **kwargs):
        self.contents = []
        for balltype in kwargs.keys():
            for ballnum in range(kwargs[balltype]):
                self.contents += balltype

hattrial = Hat(red = 1, blue = 2)
print(hattrial.contents)
        

I'm trying top create a list that contains the keys from the input argument dictionary, but instead of simply adding the string entry I get:

['r', 'e', 'd', 'b', 'l', 'u', 'e', 'b', 'l', 'u', 'e']

Instead of:

['red', 'blue', 'blue']

Where red occurs once and blue occurs twice. I've tried a few different solutions short of just manipulating the array afterwards such as the attempt below but nothing I've done has changed the output. Surely there's an elegant solution that doesn't require me sticking characters back together?

end = len(balltype)
self.contents += balltype[0:end]
self.contents += balltype

1 Answer 1

1

Using append

class Hat:
    def __init__(self, **kwargs):
        self.contents = []
        for balltype in kwargs.keys():
            for ballnum in range(kwargs[balltype]):
                self.contents.append(balltype)

hattrial = Hat(red = 1, blue = 2)
print(hattrial.contents)

Be careful with the += operator in lists

This also works, try to understand why it appends correctly here with +=

class Hat:
    def __init__(self, **kwargs):
        self.contents = []
        for balltype in kwargs.keys():
            self.contents += kwargs[balltype] * [balltype]

hattrial = Hat(red = 1, blue = 2)
print(hattrial.contents)

Basically, the problem with your code can be reduced to the following:

a = []
a += "hello"
a
['h', 'e', 'l', 'l', 'o']
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.