alex777
alex777

Reputation: 167

List object conversion to integer

I have a list:

nums=[[19],[5],[23],[6],[10]]. 

Is there a way to convert a list object to a "simple" object?

So [19] would become the actual integer 19? Maybe some type of casting?

Upvotes: 2

Views: 262

Answers (3)

Aaron Hall
Aaron Hall

Reputation: 395813

This is probably the most clear approach:

nums = [[19],[5],[23],[6],[10]]

ints = [i[0] for i in nums]

There are other instructive ways to do it as well.

Unpacking from the item works (which makes clear that there's only one element in each item, and will give an unpacking error if there is more than one):

unpacked_ints = [i for i, in nums]

Or can pop from each sublist (the last item, which removes it from the sublist, it will no longer be there if you keep around a reference to the sublists):

popped_ints = [i.pop() for i in nums]

or functionally (operator.itemgetter returns a partial function like lambda x: x[0]):

import operator
ints2 = list(map(operator.itemgetter(0), nums))

in Python2, no need for list to materialize:

import operator
ints3 = map(operator.itemgetter(0), nums)

EDIT in response to comment:

Now your comment is that you're dealing with a big iterable, probably don't want to materialize the whole thing in memory. That still doesn't change how I'd recommend you deal with it. I get the sense you'd like to be able to do this:

for i in nums:
    my_process(i)

So I would recommend you do this:

for i in nums:
    my_process(i[0])

Upvotes: 6

m.wasowski
m.wasowski

Reputation: 6386

The simplest solution is in stdlib: https://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable

import itertools
nums=[[19],[5],[23],[6],[10]]
print list(itertools.chain.from_iterable(nums))
# [19, 5, 23, 6, 10]

Upvotes: 1

timgeb
timgeb

Reputation: 78780

Another option would be to flatten the list.

nums = [[19],[5],[23],[6],[10]]
nums = [num for numlist in nums for num in numlist]

Or, but only if you want to irritate anybody reading your code:

n = [[19],[5],[23],[6],[10]]
n = [n for n in n for n in n]

;)

Upvotes: 4

Related Questions