[Tutor] Convert tuple within tuple into single tuple
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:
# if its empty do nothing
if not L: return
# if it's a list call printList on 1st element
if type(L) == type():
else: #no list so just print
print( L ) # 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.
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:
More information about the Tutor