Python list: doubles each item in a list while maintaining structure

How to write a function to double each item in a list while maintaining the list structure?

For instance:

f([1, [2, [3]]]) => [2, [4, [6]]]
+4
source share
2 answers

A simple approach could be:

def double(li):
    try:
        return [double(x) for x in li]
    except:  # li is not iterable, recursion base case
        return 2*li  # or sth. else for non-numerical, non-iterable types

Note, however, that this solution "enumerates" all kinds of iterations. A more complex version, which supports the types of your iterations, can process any nested structure of lists, tuples, sets, etc., Will have this line in the try block:

 return type(li)(map(double, li))  # should work in Python 2 and 3

This creates and returns an object of the lioriginal type (list, tuple, etc.) with a list (Py2) or a map object (Py3) of all doubled elements in li.

+4
source

, , :

def double(numberlist):
    return [double(x) if isinstance(x, list) else x * 2 for x in numberlist]

, :

from collections import Iterable
def double(numberlist):
    return [double(x) if isinstance(x, Iterable) else x * 2 for x in numberlist]
+2

All Articles