stacker
stacker

Reputation: 68972

How can a boolean be appended to a tuple?

My approach is:

def build_layers():
    layers = ()
    for i in range (0, 32):
        layers += (True)

but this leads to

TypeError: can only concatenate tuple (not "bool") to tuple

Context: This should prepare a call of bpy.ops.pose.armature_layers therefore I can't choose a list.

Upvotes: 0

Views: 4297

Answers (3)

user648852
user648852

Reputation:

Since tuples are immutable, each concatenation creates a new tuple. It is better to do something like:

def build_layers(count):
    return tuple([True]*count)

If you need some logic to the tuple constructed, just use a list comprehension or generator expression in the tuple constructor:

>>> tuple(bool(ord(e)%2) for e in 'abcdefg')
(True, False, True, False, True, False, True)

Upvotes: 1

Xavier Combelle
Xavier Combelle

Reputation: 11235

only a tuple can be add to tuple so this would be a working code

def build_layers():
    layers = ()
    for i in range (0, 32):
        layers += (True,)

However adding tuple is not very pythonic

def build_layers():
    layers = []
    for i in range (0, 32):
        layers.append(True)
    return tuple(layers)

if the True value depend on i you can make a function

def f(i):
    True

def build_layers():
    layers = []
    for i in range (0, 32):
        layers.append(f(i))
    return tuple(layers)

but this is typically best suited in a generator expression

def build_layers():
    return tuple(f(i) for i in range(0,32))

by the way the start value of a range is default 0

so this equally work

def build_layers():
    return tuple(f(i) for i in range(32))

Upvotes: 1

user1907906
user1907906

Reputation:

(True) is not a tuple.

Do this instead:

layers += (True, )

Even better, use a generator:

(True, ) * 32

Upvotes: 5

Related Questions