Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert n-tuple to x-tuple where x < n

The question is pretty straightforward (unlike the title). I have a tuple of the type:

p = (1, 2, 3, 4, 5, 6)
# I refer to this as a 6-tuple but p could be an n-tuple

I need to convert this into a smaller tuple like:

(a, b) = p

such that a <- 1 and b <- (2, 3, 4, 5, 6)

EDIT:

I need code for Python v2.7. Also, I should have mentioned that there are ways to do it but I am looking for something natural and something where I don't need to deal with indices. For example.

a, b, c, d, e = p[0], p[1], p[2], p[3], p[4], p[5:]

is not desired.

EDIT 2:

In the above example, a is an integer whereas b is our new tuple. The idea behind n-tuple to x-tuple is that the length of the new tuple is smaller than the original one. In the following example we have 0-tuples (ints):

a, b, c = (1, 2, 3)

However, if it's the following:

a, b, c, d = (1, 2, 3)

then, we have a <- 1, b <- 2, c <-3, d <- None/Nothing.

like image 601
p0lAris Avatar asked Feb 06 '26 21:02

p0lAris


2 Answers

For a general solution:

def split_after(lst, n):
    for i in range(n):
        yield lst[i]
    yield lst[n:]

Result:

>>> a,b,n = split_after(p,2)
>>> a
1
>>> b
2
>>> n
(3, 4, 5, 6)
>>> l = list(split_after(p,3))
>>> l
[1, 2, 3, (4, 5, 6)]

So you need to know how many items you have on the left-hand side and tell that to the function (because it can't tell that by itself, unlike what the extended tuple unpacking syntax in Python 3 allows you to do).

like image 152
Tim Pietzcker Avatar answered Feb 09 '26 10:02

Tim Pietzcker


You can do this

a, b = p[0], p[1:]

This is example

>>> p = (1,2,3,4,5)
>>> a, b = p[0], p[1:]
>>> a
1
>>> b
(2, 3, 4, 5)
like image 30
Deck Avatar answered Feb 09 '26 11:02

Deck