Moonie
Moonie

Reputation: 1

Can't stop python from iterating through string in loop

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

Upvotes: 0

Views: 138

Answers (1)

Norhther
Norhther

Reputation: 500

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']

Upvotes: 1

Related Questions