2

I have a tuple, which consists of some tuple of integers and some integers, like ((1, 2), 3, (4, 5), 6).Now I need all integers from it. I wrote:

def get_all_items(iterable):
    t = []

    for each in iterable:
        if type(each) == int:
            t.append(each)
        else:
            t.extend(each)

    return tuple(t)

It works for me. Is there any better way to do this?

1
  • 1
    Do you know for sure that there is only one level of hierarchy, i.e., you don't have a tuple of tuples of tuples? Commented Oct 15, 2013 at 3:23

5 Answers 5

3

Don't forget the cheats way

>>> from ast import literal_eval
>>> t = ((1, 2), 3, (4, 5), 6)
>>> literal_eval(repr(t).translate(None, '()'))
(1, 2, 3, 4, 5, 6)
Sign up to request clarification or add additional context in comments.

1 Comment

It's not often that code makes me laugh... I think what got me is "the cheats way"
1

I think your way is fine. Here's another way, using recursion, which will work for an arbitrarily-deeply-nested iterable structure:

def get_all_items(iterable):
    try:
        result = []
        for element in iterable:
            result += detuple(element)
        return result
    except TypeError:
        return [iterable]

Also, it may be useful to know that the operation you're describing is known as "flattening" a data structure.

Comments

1
from itertools import chain

def flatten(items):
  def renest():
    for item in items:
      try:
        yield iter(item)
      except TypeError:
        yield iter([item])
  return list(chain.from_iterable(renest()))

2 Comments

@DSM yeah, I forgot itertools wasn't magic.
Easy to forget, because it so often is. :^)
1
import itertools
itertools.chain.from_iterable(
    item if hasattr(item, '__iter__') else (item,)
        for item in iterable 
)

Comments

1

You can simplify your code like this

def get_all_items(iterable):
    t = []
    for each in iterable:
        t.extend(list(each) if isinstance(each, tuple) else [each])
    return tuple(t)

print get_all_items(((1, 2), 3, (4, 5), 6))

Output

(1, 2, 3, 4, 5, 6)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.