How to Create String Array in Python ?
In Python programming, a String is a data type used to store a series of characters. So sometimes a need may arise where we need an array of strings. An array is a collection of elements of the same data type. The simplest way is a list of similar elements.
Let us explore how to create a String array in Python.
a = ["Geeks", "for", "Geeks"]
print(a)
Output
['Geeks', 'for', 'Geeks']
Explanation:
- In the above example, we created a list of string elements that act as an array in Python.
Now let us see different ways to create a string array in Python.
Table of Content
Using List
The simplest and easiest way to create any type of array in Python is by using List data structure. It is the most widely used method to create an array. There are various ways to create array using list.
1. Direct Initialization
In this method, when a list array is created, the values are assigned during the declaration. Later on an element can be added or removed from this array.
arr = ["Geeks", "for", "Geeks"]
print(arr[1])
Output
for
2. Using append()
Another way to create a string array is by starting with an empty list and using the append() method to add elements dynamically.
# empty list (array)
arr = []
# elemnts of the array
arr.append("Geeks")
arr.append("for")
arr.append("Geeks")
print(arr)
print(arr[2])
Output
['Geeks', 'for', 'Geeks'] Geeks
3. Using List Comprehension
In this method, we first create an empty array using list comprehension and specifying the length of the array. Then we can use list indexing method to replace those empty spaces with the actual string values.
# fixed length empty string array
arr = ["" for i in range(5)]
print(arr)
# replacing values of the array
arr[0] = "Geeks"
arr[1] = "for"
arr[4] = "Geeks"
print(arr)
Output
['', '', '', '', ''] ['Geeks', 'for', '', '', 'Geeks']
Using Numpy Arrays
Numpy module in Python is used for working with array. Using the numpy module's array() function, a string array can be created easily.
import numpy as np
arr = np.array(["Geeks","for","Geeks"])
print(arr)
print(arr[2])
Output
['Geeks' 'for' 'Geeks'] Geeks
Using Array Module
Python array module is specifically used to create and manipulate arrays in Python. Although the array module does not support string datatype, but it can be modified to store the Unicode characters as strings.
from array import array
arr = array('u', "GeeksforGeeks")
print(arr[4])
Output
s
Note: The String array created using the array module cannot store multiple string values, but rather takes a string and stores its individual characters as elements.