Casa > H > How To Give Input To An Array In Python

How to give input to an array in Python

Read Carefully.

1. Python add to Array

  • If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List.
  • If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array.
  • If you are using NumPy arrays, use the append() and insert() function.

2. Adding elements to an Array using array module

  • Using + operator: a new array is returned with the elements from both the arrays.
  • append(): adds the element to the end of the array.
  • insert(): inserts the element before the given index of the array.
  • extend(): used to append the given array elements to this array.
  1. import array 
  2.  
  3. arr1 = array.array('i', [1, 2, 3]) 
  4. arr2 = array.array('i', [4, 5, 6]) 
  5.  
  6. print(arr1) # array('i', [1, 2, 3]) 
  7. print(arr2) # array('i', [4, 5, 6]) 
  8.  
  9. arr3 = arr1 + arr2 
  10. print(arr3) # array('i', [1, 2, 3, 4, 5, 6]) 
  11.  
  12. arr1.append(4) 
  13. print(arr1) # array('i', [1, 2, 3, 4]) 
  14.  
  15. arr1.insert(0, 10) 
  16. print(arr1) # array('i', [10, 1, 2, 3, 4]) 
  17.  
  18. arr1.extend(arr2) 
  19. print(arr1) # array('i', [10, 1, 2, 3, 4, 4, 5, 6]) 

3. Adding elements to the NumPy Array

  • append(): the given values are added to the end of the array. If the axis is not provided, then the arrays are flattened before appending.
  • insert(): used to insert values at the given index. We can insert elements based on the axis, otherwise, the elements will be flattened before the insert operation.
  1. >>> import numpy as np 
  2. >>> np_arr1 = np.array([[1, 2], [3, 4]]) 
  3. >>> np_arr2 = np.array([[10, 20], [30, 40]]) 
  4. >>>  
  5. >>> np.append(np_arr1, np_arr2) 
  6. array([ 1, 2, 3, 4, 10, 20, 30, 40]) 
  7. >>> 
  8. >>> np.append(np_arr1, np_arr2, axis=0) 
  9. array([[ 1, 2], 
  10. [ 3, 4], 
  11. [10, 20], 
  12. [30, 40]]) 
  13. >>> 
  14. >>> np.append(np_arr1, np_arr2, axis=1) 
  15. array([[ 1, 2, 10, 20], 
  16. [ 3, 4, 30, 40]]) 
  17. >>>  
  18. >>> np.insert(np_arr1, 1, np_arr2, axis=0) 
  19. array([[ 1, 2], 
  20. [10, 20], 
  21. [30, 40], 
  22. [ 3, 4]]) 
  23. >>>  
  24. >>> np.insert(np_arr1, 1, np_arr2, axis=1) 
  25. array([[ 1, 10, 30, 2], 
  26. [ 3, 20, 40, 4]]) 
  27. >>>  

De Bounds

Como transpor um array em Python :: Quais são os melhores aplicativos gratuitos para edição de vídeo para um vídeo de culinária no YouTube?