Convert Any Iterable to Array in Python

12,475

Solution 1

It depends on what you mean by array. If you really mean array and not list or the like, then you should be aware that arrays are containers of elements of the same (basic) type (see http://docs.python.org/library/array.html), i.e. not all iterables can be converted into an array. If you mean list, try the following:

l = list(iterable)

Solution 2

If by "array" you mean a list, how about:

list(foo)

Solution 3

What about [e for e in iterable]?

And, to satisfy the extra requirement:

iterable if isinstance(iterable,list) else [e for e in iterable]

Solution 4

The list function takes an iterable as an argument and returns a list. Here's an example:

>>> rng = xrange(10)
>>> rng
xrange(10)
>>> list(rng)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

This won't create a list of lists, either:

>>> list(list(rng))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Share:
12,475
user541686
Author by

user541686

Updated on August 09, 2022

Comments

  • user541686
    user541686 over 1 year

    This just has to be a dupe, but I just didn't find any existing instance of this question...

    What is the easiest way to convert any iterable to an array in Python (ideally, without importing anything)?

    Note: Ideally, if the input is an array then it shouldn't duplicate it (but this isn't required).

  • Thomas Wouters
    Thomas Wouters almost 13 years
    [e for e in iterable] is better written as list(iterable).