We create arrays to store and work with many numbers together easily. Arrays help us do math and analyze data faster.
Array creation (array, arange, linspace) in Data Analysis Python
import numpy as np # Create an array from a list array = np.array([1, 2, 3, 4]) # Create an array with numbers from start to stop (exclusive) with step size arange_array = np.arange(start, stop, step) # Create an array with a specific number of points between start and stop (inclusive) linspace_array = np.linspace(start, stop, num=num_points)
np.array converts a list or tuple into an array.
np.arange creates numbers with a fixed step size but excludes the stop value.
import numpy as np # Empty array from empty list empty_array = np.array([]) print(empty_array)
import numpy as np # Array with one element single_element_array = np.array([10]) print(single_element_array)
import numpy as np # arange from 0 to 5 with step 1 range_array = np.arange(0, 5, 1) print(range_array)
import numpy as np # linspace from 0 to 1 with 5 points linspace_array = np.linspace(0, 1, 5) print(linspace_array)
This program shows how to create arrays using three methods: from a list, with fixed steps, and with a fixed number of points.
import numpy as np # Create an array from a list numbers_list = [2, 4, 6, 8] numbers_array = np.array(numbers_list) print("Array from list:", numbers_array) # Create an array using arange from 1 to 10 with step 2 arange_array = np.arange(1, 10, 2) print("Arange array:", arange_array) # Create an array using linspace from 0 to 5 with 6 points linspace_array = np.linspace(0, 5, 6) print("Linspace array:", linspace_array)
Time complexity: Creating arrays is fast and usually O(n), where n is the number of elements.
Space complexity: Arrays use memory proportional to the number of elements stored.
Common mistake: Using np.arange with floating point steps can cause unexpected results due to rounding errors. Use np.linspace for precise spacing.
Use np.array to convert existing data. Use np.arange when you want a range with a fixed step size. Use np.linspace when you want a fixed number of points between two values.
Arrays store many numbers together for easy math and analysis.
np.array converts lists to arrays.
np.arange creates sequences with fixed steps, excluding the stop value.
np.linspace creates sequences with a fixed number of points including start and stop.