← Back to NumPy Course | Chapter 2: Creating Arrays | Lesson 7 of 7

Array from list/tuple

Lists and tuples both convert to arrays, and nesting them makes rows and columns.

In this page:

  1. Array from list/tuple
Syntax
python
arr = np.array((value1, value2, value3))
matrix = np.array([(a, b), (c, d)])

Array from list/tuple

np.array accepts any sequence, including tuples, lists of tuples and mixed nested sequences. np.asarray does the same without copying when possible. np.fromiter builds an array from any iterable.

Note: Use np.array(list(range(5))) or simply np.arange(5) for ranges.

Example: Array from list/tuple

python
import numpy as np

from_list = np.array([1, 2, 3])
from_tuple = np.array((4, 5, 6))
grid = np.array([(1, 2), (3, 4)])
mixed = np.array([1, "a"])

print(from_list, from_tuple)
print(grid)
print(mixed, mixed.dtype)

# Output:
# [1 2 3] [4 5 6]
# [[1 2]
#  [3 4]]
# ['1' 'a'] <U21
Related Topics
Common Mistakes
  1. Mixing strings and numbers and getting a string array
  2. Providing rows of different lengths
  3. Assuming a tuple stays a tuple
Chapter Summary
  • Lists and tuples convert equally
  • Nested sequences give 2-D arrays
  • asarray avoids needless copies
  • Mixed strings and numbers become strings
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.