1

I want to extend the list

s = 0,1

def hi(x):
    global s
    for i in range(x):
        s = 0,s
    return s

print hi(5)

the result of this will be '(0, (0, (0, (0, (0, (0, 1))))))'

But what I really want is (0, 0, 0, 0, 0, 0, 1). Do you have any idea doing it?

Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
Kenta Nomoto
  • 839
  • 6
  • 11

3 Answers3

2

you could do: s= (0,)+s to create a new tuple with leading 0 (instead of nesting the tuple at each iteration like you're doing.

But maybe the best way would be to prepend with a tuple of zeroes using multiplication (to avoid the loop):

s = (0,)*x + s

what bothers me even more is the need to use a global. I would pass s as a parameter:

def hi(x,s):
    return (0,)*x + s

print(hi(5,(0,1)))

resulting in the following tuple:

(0, 0, 0, 0, 0, 0, 1)

you may want to read about lists and tuples and their differences: What's the difference between lists and tuples?. It's much easier to work with lists because of the available in-place operations they offer (but they cannot be used as dictionary keys or to be stored in sets)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

s = 0, 1 is not a list but a tuple which is immutable.

It would be better to use proper list s = [0, 1] and then use insert() method.

def hi(x, s):
    for _ in range(x):
        s.insert(0, 0)
    return s

Or event better to avoid the for loop:

def hi(x, s):
    return ([0] * x) + s

If you want to use a tuple, then the answer from @Jean-François Fabre is the way to go.

FabienP
  • 3,018
  • 1
  • 20
  • 25
0

Given your particular use case Jean's answer would be better. But if you want to make that nested tuple into a single dimensional tuple, the more canonical operation is called flatten(). flatten() takes an arbitrarily-nested sequence and 'flattens' it into sequence with no nesting. flatten() isn't included in the python standard libraries, but is an incredibly useful operation included in many other languages. I took this below implementation from here, which includes other implementations and discusses their strengths and weaknesses.

def flatten(l, ltypes=(list, tuple)):
    ltype = type(l)
    l = list(l)
    i = 0
    while i < len(l):
        while isinstance(l[i], ltypes):
            if not l[i]:
                l.pop(i)
                i -= 1
                break
            else:
                l[i:i + 1] = l[i]
        i += 1
    return ltype(l)

The usage is simple:

a = ((1, 2), (3,), (4, (5, 6)))
flatten(a)  # -> (1, 2, 3, 4, 5, 6)

a = hi(6)   # -> (0, (0, (0, (0, (0, (0, 1))))))
flatten(a)  # -> (0, 0, 0, 0, 0, 0, 1)
ktb
  • 1,498
  • 10
  • 27