1
    def digit_sum(n):
        n = str(n)
        empty = [x.split() for x in n]
        print empty



    digit_sum(21)

This code will output:

     [['2'], ['1']]

What I need is to make it:

    [2, 1] 

so I can add the numbers in the list together. How do I do that?

jped
  • 103
  • 2
  • 5

6 Answers6

3

I would just do (you don't need to .split it, just convert it to a string over which you can iterate):

def digit_sum(n):
    empty = [int(d) for d in str(n)]
    print empty

Demo:

>>> digit_sum(21)
[2, 1]

You could then obviously add them together with the sum() function.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
2

Don't call split. Split tries to divide a string on whitespace (by default). It will return a list of strings always (even if there were no splits to be made).

Since your loop is over a string, x will be a single character. That means you'll never have any whitespace to split on.

Just do [x for x in n] or list(n).

Or if you want your digits as integers, rather than strings: [int(x) for x in n] or map(int, n)

Blckknght
  • 100,903
  • 11
  • 120
  • 169
0

I believe if you

firstlist.append(secondlist)

Python should print 1, 2. Posting from a Windows Phone, so I can't run the code, excuse my incompetence if this doesn't work.

0

This works:

def digit_sum(n):
  n = str(n)
  empty = [int(x) for x in n]
  print empty

digit_sum(21)

Output:

[2,1]

split returns a list. for x in n will go over each character in the string and int(x) converts the character to an integer.

hmatt1
  • 4,939
  • 3
  • 30
  • 51
0
>>> from itertools import chain
>>> x = [['2'], ['1']]
>>> map(int, chain(*x))
[2, 1]
alvas
  • 115,346
  • 109
  • 446
  • 738
0

If you want to completely flatten a list of lists, you need to check if its iterable.

To do this you can create a generator which returns a non-iterable item, or recursively calls itself if the item is iterable.

Then place each element of the generator in a list, and print it.

Warning!!

This will crash with cycling lists ie l = []; l.append(l)

def get_single_elements(item):
    if hasattr(item, '__iter__'):
        for child_item in item:
            for element in get_single_elements(child_item):
                yield element
    else:
        yield item

def print_flat(item):
    print [element for element in get_single_elements(item)]
    

>>> print_flat([[[0],[1]]])
[0, 1]
>>> print_flat([[[[[0,[1,2,[3,4]]]]],[[1]]]])
[0, 1, 2, 3, 4, 1]

Edit if you're sure you want to convert all items to ints, then write it like this

def print_flat(item):
        print [int(element) for element in get_single_elements(item)]
Community
  • 1
  • 1
flakes
  • 21,558
  • 8
  • 41
  • 88