-2

How do I make a string array in python with length 100 for example. I don't use python much so I'm not really sure how. I want the array to be formatted in this way so I can assign a string to a value in a separate line.

keyword = [100]
keyword[0] = "Blue Light Glasses"
keyword[1] = "Tech Fleece Joggers"
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    You can use something like `[None] * 100` and then reassign elements as necessary. – BrokenBenchmark Feb 12 '22 at 18:16
  • If you don't need random access for construction, just `keyword = []` then `keyword.append(string)` as needed. Or if the strings are known in advance, just `keyword = ['string1','string2']`. – Mark Tolonen Feb 12 '22 at 18:17
  • 1
    I’ll add that this is something that is rarely needed in Python. It feels like an xy problem. – Mark Feb 12 '22 at 18:18

2 Answers2

0

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']
Shrmn
  • 368
  • 4
  • 12
0

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
Rom7x
  • 56
  • 1
  • 6