7

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).

user541686
  • 205,094
  • 128
  • 528
  • 886

5 Answers5

19

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)
jena
  • 8,096
  • 1
  • 24
  • 23
4

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

list(foo)
Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
2

What about [e for e in iterable]?

And, to satisfy the extra requirement:

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

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
2

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]
jterrace
  • 64,866
  • 22
  • 157
  • 202
0

Basically, arrays and lists are more or less the same thing in python. So a list comprehension will do the job:

  ary = [ i for i in yourthing ]
Charlie Martin
  • 110,348
  • 25
  • 193
  • 263