Skip to content Skip to sidebar Skip to footer

Can I Store Strings In Python Array?

from array import * val=array('u',['thili','gfgfdg']) print(val) When I compiled above python code, the compiler showed an error. What is the problem in my code.can not store st

Solution 1:

Firstly, the Python interpreter is written in C language language and that array library is includes array of C language (In fact, it is not array of Python, it is array of C). A string is array of chars in C (char is a number which act like one letter). You are passing two unicode strings as argument to the array function but one of these unicode strings is already an array for C. So you cant pass two unicode string to array function. Look at that:

from array import array
my_array = array("u","thili") # no errorprint(my_array) # array('u', 'thili')

other_array = array("u",["thili","gfgfdg"])
Traceback (most recent call last):
  File "<pyshell#5>", line 3, in <module>
    my_array = array("u",["thili",""])
TypeError: array item must be unicode character

As you can see array of unicode string is not much different than normal unicode string. Because it contains only one string. You should use list or tuple class instead. And the list class in Python is array of Python.

my_list = ["thili","gfgfdg"] # same as: my_list = list("thili","gfgfdg")
my_tuple = ("thili","gfgfdg") # same as: my_tuple = tuple("thili","gfgfdg")

Dont forget that tuples are unmutable but lists are mutable. If you want to change value of any index, then use list. Tuples are good when you want to optimize your memory (RAM) usage. Finally tuples are more faster than lists in terms of creation.

Solution 2:

You can not find anything faster or not by using timeit module in python or any programming language because time taken directly depends upon your machine configuration so for checking that thing we use time complexity in programming...

Post a Comment for "Can I Store Strings In Python Array?"