Python – Create a Character Array

Create a Character Array in Python

In Python, you can create a unicode character array using array() method of array module.

In this tutorial, you will learn how to create a Python array with character values in it, with examples.

To create a unicode character array in Python, import array module, call array() method of array module, and pass the 'u' type code as first argument, and the list of unicode character values for the initial values of array as second argument.

array('u', initial_values)

Initial values (second argument) to the array() method is optional. If you do not pass any initial values, then an empty character array would be created.

1. Create a character array with initial values

In the following program, we create an integer array my_array using array() method. Pass 'i' type code as first argument to the array() method, and pass a list of initial values to the array as second argument to the array() method.

Python Program

import array as arr

my_array = arr.array('u', ['a', 'p', 'p', 'l', 'e'])

print(my_array)
Run Code Copy

Output

array('u', 'apple')

To initialize a character array, we can also pass a string, instead of a list of character strings, as shown in the following program.

Python Program

import array as arr

my_array = arr.array('u', 'apple')

print(my_array)
Run Code Copy

Output

array('u', 'apple')

2. Create an empty character array and add values

We can also create an empty character array, and then append values to the array.

In the following program, we create an empty character array my_array, and then add some character values to this array.

Python Program

import array as arr

my_array = arr.array('u')
my_array.append('a')
my_array.append('p')
my_array.append('p')
my_array.append('l')
my_array.append('e')

print(my_array)
Run Code Copy

Output

array('u', 'apple')

3. Iterate over Character Array

We can use a For loop to iterate over the elements of a character array.

In the following program, we take a character array my_array, and then use a For loop to iterate over the character elements in the array.

Python Program

import array as arr

my_array = arr.array('u', 'apple')

for element in my_array:
    print(element)
Run Code Copy

Output

a
p
p
l
e

Summary

In this Python Array tutorial, we learned how to create a unicode character array in Python, using array() method of array module, with examples.

Related Tutorials

Code copied to clipboard successfully 👍