Nick Kremer
Nick Kremer

Reputation: 223

Unpacking a tuple containing integers to a list

I am trying to create a single list with a tuple that contains integers

Examples of input:

test1((1, 2, 3), 2, 3)

test2((5, -5), 10, 3)

test3((10.2, -2.2, 0, 1.1, 0.5), 12.4, 3)

I have tried iterating through the tuple in various ways, but get a "int() is not iterable error". I tried to assign variables to inputs but get an "'type' object is not subscriptable" error.

I've rewritten the script many times now and don't have previous attempts saved. The unpack methods I've found on here don't work because they require me to iterate through the input, which I cannot do (or figure out how). b = [i for sub in args for i in sub], list(chain.from_iterable(args) ect haven't worked.

Here is what I have now

def checkio(*args):
    ab, cd, ef = args
    print (ab)
    empty = []
    empty.append(cd)
    empty.append(ef)
    for i in ab:
        empty.append(i)
    print (empty)

A bit of a mess. I'm quite new to python so I'm sure the solution is very simple

Upvotes: 1

Views: 1249

Answers (3)

Jason
Jason

Reputation: 3535

Have you tried this:

a = (1,2,3)
b = [*a]
print(b)

it converts the tuple to list. or simply print(*a)

Upvotes: 0

Kobi K
Kobi K

Reputation: 7931

If the pattern is always tuple which can be one of 2:

  • Tuple
  • Number

you can do the following more generic solution:

my_tuple = ((10.2, -2.2, 0, 1.1, 0.5), 12.4, 3)
my_list = []
for v in my_tuple:
    if isinstance(v, tuple):
        my_list.extend += v
    else:
        my_list.append(v)

print my_list

Output:

[10.2, -2.2, 0, 1.1, 0.5, 12.4, 3]

It's a question of pattern and how your data is struct.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122512

If your input is as regular as your samples, the answer is simple; create a new tuple by concatenating:

def checkio(ab, cd, ef):
    return ab + (cd, ef)

This concatenates a new tuple with (cd, ef) to the existing ab tuple.

For different patterns, you'll need to test the values; if all you ever get is tuples or integers, and the tuples are not nested, then that's as simple as:

def checkio(*args):
    result = []
    for value in args:
        if isinstante(value, tuple):
            result += value
        else:
            result.append(value)
    return tuple(result)

You can fight recursion with recursion; if the tuples can contain other tuples, flatten them with a recursive function:

def checkio(*args):
    result = []
    for value in args:
        if isinstante(value, tuple):
            result += checkio(*value)
        else:
            result.append(value)
    return tuple(result)

Upvotes: 1

Related Questions