ragingcorgi
ragingcorgi

Reputation: 3468

How to convert an int to a list?

I have some code that might return either a single int, or a list. When it returns an int, I need to convert it into a list that contains only the int.

I tried the following, but it doesn't work:

newValue = list(retValue)

Apparently I can't do list(some int) because ints are not iterable. Is there another way of doing this?

Thanks in advance!

Upvotes: 0

Views: 813

Answers (6)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

define your own function:

 def mylist(x):
    if isinstance(x,(list,tuple)):
        return x
    else:
        return [x]


>>> mylist(5)
[5]
>>> mylist([10])
[10]

Upvotes: 9

senderle
senderle

Reputation: 150957

This is really just a variation on Hugh Bothwell's answer, but... if you want state-of-the-art duck typing, you can get the semantics of hasattr(rval, '__iter__') in a more attractive package with isinstance(rval, collections.Iterable). So...

def wrap_in_iterable(x):
    if isinstance(x, collections.Iterable):
        return x
    else:
        return [x]

Also, perhaps you want a list, and not just an iterable; to get list-like things but eliminate generator-like and dict-like things, collections.Sequence is handy. (Just don't pass an infinite generator to this function.)

def convert_to_sequence(x):
    if isinstance(x, collections.Sequence):
        return x
    elif isinstance(x, collections.Iterable):
        return list(x)
    else
        return [x]

These work because collections.Sequence and collection.Iterable define __subclasshook__s that perform the appropriate hasattr checks.

Finally, at the risk of being boring -- if you have control over the returning function, just return a one-item list if possible.

Upvotes: 2

Marcin
Marcin

Reputation: 49816

if isinstance(x,list): return x
else: return [x]

That's it.

Of course, this won't deal intelligently with other iterable types, but it's not clear that you want to treat all iterables as if they were lists (maybe you do, maybe you don't).

Upvotes: 2

Sumit Purohit
Sumit Purohit

Reputation: 168

listInt = intVal if isinstance(intVal,list) else [intVal]

this will always return a list if value is not a list. Hope this helps

Upvotes: 2

Hugh Bothwell
Hugh Bothwell

Reputation: 56634

In Python, duck typing is preferable - don't test for a specific type, just test whether it supports the method you need ("I don't care if it's a duck, so long as it quacks").

def make_list(n):
    if hasattr(n, '__iter__'):
        return n
    else:
        return [n]

a = make_list([1,2,3])    # => [1,2,3]
b = make_list(4)          # => [4]

Upvotes: 7

Dunes
Dunes

Reputation: 40683

Try to convert the variable to an int. If it is already an int this is a no-op. If it is a list then this raises a TypeError.

try:
    return [int(x)]
except TypeError:
    return x

Though using exceptions for flow control is generally frowned upon if the exceptional circumstance has a high probability of occurring. This is because processing exceptions is quite a lengthy task.

The other way is to use the isinstance operator.

if isinstance(x, list):
    return x
else:
    return [x]

Upvotes: 2

Related Questions