0

Consider I have a list like

listed = [1, 't', 'ret', 89, 95, 'man65', 67, 'rr']

Now I need to write a script which will be like 2 lists; one stringList and numberList where,

stringList = ['t', 'ret', 'man65', 'rr']
numberList = [1, 89, 95, 67]
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Bharath Kashyap
  • 343
  • 2
  • 5
  • 14

5 Answers5

6

The standard way to check what kind of object you have is by using the isinstance(object, classinfo) function. Using isinstance(...) is preferred over type(object) because type(...) returns the exact type of an object, and does not account for sub-classes when checking types (this is significant in more complex scenarios).

You can check if you have a number (int, float, etc.) by comparing each class individually or with numbers.Number:

# Check for any type of number in Python 2 or 3.
import numbers
isinstance(value, numbers.Number)

# Check for floating-point number in Python 2 or 3.
isinstance(value, float)

# Check for integers in Python 3.
isinstance(value, int)

# Check for integers in Python 2.
isinstance(value, (int, long))

You can check if you have a string (str, bytes, etc.) by comparing with the individual classes which vary depending on whether you're using Python 2 or 3:

# Check for unicode string in Python 3.
isinstance(value, str)

# Check for binary string in Python 3.
isinstance(value, bytes)

# Check for any type of string in Python 3.
isinstance(value, (str, bytes))

# Check for unicode string in Python 2.
isinstance(value, unicode)

# Check for binary string in Python 2.
isinstance(value, str)

# Check for any type of string in Python 2.
isinstance(value, basestring)

So, putting that all together you'd have:

import numbers

stringList = []
numberList = []
for value in mixedList:
    if isinstance(value, str):
        stringList.append(value)
    elif isinstance(value, numbers.Number):
        numberList.append(value)
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
  • note in Python 2 you should use `basestring` instead of `str` ...and in Py 3 I think you should use a tuple of `(str, bytes)` http://www.rfk.id.au/blog/entry/preparing-pyenchant-for-python-3/ – Anentropic May 14 '15 at 13:32
2
numbers, strings = both = [], []
for x in listed:
    both[isinstance(x, str)].append(x)

An alternative as an answer to Ajay's challenge in the comments to do it with just one list comprehension (note: this is a bad solution):

strings = [listed.pop(i) for i, x in list(enumerate(listed))[::-1] if isinstance(x, str)][::-1]
numbers = listed

Another:

numbers, strings = [[x for x in listed if isinstance(x, t)] for t in (int, str)]

Yet another, with the advantage of reading listed only once (inspired by PM 2Ring):

numbers, strings = [[x for x in l if isinstance(x, t)]
                    for l, t in zip(itertools.tee(listed), (int, str))]
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
1

You can use the built in type function to test each element in the list, and append it to a list based in its type.

numberList = []
stringList = []

for x in listed:
    if type(x) == int: numberList.append(x)
    else: stringList.append(x)
Tom
  • 918
  • 6
  • 19
  • 1
    Using `isinstance()` is perferred over checking with `type()` because `isinstance()` can handle subclasses while `type()` checks the exact type. – Uyghur Lives Matter May 14 '15 at 13:33
  • @cpburnz True but in the OP's example he only has ints and strings. But I will note isinstance for the future, as I did not know about isinstance. – Tom May 14 '15 at 13:38
  • For further info on `isinstance()` vs type`()` please see http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python – PM 2Ring May 14 '15 at 13:47
  • @PM2Ring Thanks i'll have a look – Tom May 14 '15 at 13:52
1
In [16]: sl=[i for i in a if isinstance(i,str)]

In [17]: nl=[i for i in a if isinstance(i,int)]

In [18]: sl
Out[18]: ['t', 'ret', 'man65', 'rr']

In [19]: nl
Out[19]: [1, 89, 95, 67]
Ajay
  • 5,267
  • 2
  • 23
  • 30
1

Generic solution: grouping by exact object type.

multityped_objects = [1, 't', 'ret', 89, 95, 'man65', 67, 'rr', 12.8]
grouped = {}
for o in multityped_objects:
    try:
        grouped[type(o)].append(o)
    except KeyError:
        grouped[type(o)] = [o]

assert grouped[str] == ['t', 'ret', 'man65', 'rr']
assert grouped[int] == [1, 89, 95, 67]
assert grouped[float] == [12.8]
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93