Array from list/tuple
Lists and tuples both convert to arrays, and nesting them makes rows and columns.
In this page:
Syntax
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
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
- Mixing strings and numbers and getting a string array
- Providing rows of different lengths
- 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: