Convert a List to an Array in Python

  • Post category:List

Converting a list to an array is a common task in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to convert a list to an array efficiently.

Example 1:

import array

numbers = [1, 2, 3, 4, 5]
numbers_array = array.array('i', numbers)
print(numbers_array)

Output: array(‘i’, [1, 2, 3, 4, 5])

Example 2:

import array

fruits = ['apple', 'banana', 'orange', 'kiwi']
fruits_array = array.array('u', ''.join(fruits))
print(fruits_array)

Output: array(‘u’, ‘applebananaorangekiwi’)