[Tutor] Convert tuple within tuple into single tuple

Alan Gauld alan.gauld at yahoo.co.uk
Wed Jan 11 14:57:51 EST 2017


On 11/01/17 06:31, ramakrishna reddy wrote:
> Hi All,
> 
> Is there any way to convert x = (1, 2, 3, (4, 5)) to x = (1, 2, 3, 4, 5) in
> python 2.7

You can write a function(*) to flatten the data structure,
but you need to be careful and think through how you
expect it to handle strings, say... or dictionaries?
Or user defined collection objects?

That's probably why there is no built-in method to flatten
a data structure.

Such functions are often recursive in nature looking
something like this list based example from my tutorial:

def printList(L):
    # if its empty do nothing
    if not L: return
    # if it's a list call printList on 1st element
    if type(L[0]) == type([]):
        printList(L[0])
    else: #no list so just print
        print( L[0] ) # now process the rest of L
    printList( L[1:] )

Obviously that prints rather than building a new list
but it should be fairly easy to modify it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list