If you fix the lenght of the array, you can just create a list with a none value
keyword = [''] * 100 # list of 100 element
keyword[0] = 'Blue Light Glasses'
keyword[1] = "Tech Fleece Joggers"
You can also create a empty list and add element in this list
keyword = list()
keyword.append('Blue Light Glasses')
keyword.append('Tech Fleece Joggers')
print(keyword)
Output:
['Blue Light Glasses', 'Tech Fleece Joggers']
Answer from Shrmn on Stack OverflowIf you fix the lenght of the array, you can just create a list with a none value
keyword = [''] * 100 # list of 100 element
keyword[0] = 'Blue Light Glasses'
keyword[1] = "Tech Fleece Joggers"
You can also create a empty list and add element in this list
keyword = list()
keyword.append('Blue Light Glasses')
keyword.append('Tech Fleece Joggers')
print(keyword)
Output:
['Blue Light Glasses', 'Tech Fleece Joggers']
there isn't a way in python to declare a array of a fixed lenght but there are some "tricks" to do this as:
lenght = 100
# You are creating an array of 100 None items
listOfNone = [None] * lenght
Another thing you can't do is declare an array of that fixed value type (like string). You can create an array only made of string but at any time you could replace a string element of the array with an int for example. Here is an example:
lenght = 100
# Declaring an array made of 100 "a beautiful string" repeating
listOfStrings = ["a beautiful string"] * lenght
# Replacing the tenth element with a 12 (type int)
listOfStrings[9] = 12
# You can check the type of the element in python by printing:
print(type(listOfStrings[9])) # This will print int
print(type(listOfStrings[8])) # This will print string. As you can see there are 2 types of var in the same list (python doesn't matter)
listOfStrings[24] = False #Placing a bool in the 25th element
There is a workaround to this: you can create a function that handles the array (or use a class too, but I don't know your Python level). I'm typing a basic function for you that you can adjust for your needs
def fillArrayWithElement(array, element):
if not str(type(array)) == "<class 'list'>":
# The array is not an array
raise ValueError('The first parameter must be list type')
return
if not str(type(prova2)) == "<class 'str'>":
# The element to add is not a string
raise ValueError('The element must be str type')
return
array.append(element)
return array
Can't get string array to print
How do I convert Numpy Array to a List of Strings?
Just a little pixelart to python array of strings converter I made this weekend, so you can display your pixelarts in the python's command line interface
How to decode a numpy array of encoded literals/strings in Python3?
Videos
I am currently using np.array(x).to list() and that is printing as [a, b]. I want the output to be a list of strings so that it prints as ['a', 'b']. Any advice? Thank you