1

I'm trying to get a better grasp on the data structures. I've been trying to add an array as an element of another array, but i keep getting the TypeError: Array item must be unicode character, when I try to create an array. I'm following videos/everything I read to a T from what i can tell.

from array import array

Swords = array('u',['Steel Sword', 'Bronze Sword', 'Iron Sword'])
Axes = ['Steel Axe', 'Bronze Axe', 'Iron Axe']
Maces = ['Steel Mace','Bronze Mace','Iron Mace']
Bows = ['Wood Bow', 'Bone Bow', 'Obsidian Bow']
Daggers = ['Steel Dagger', 'Bronze Dagger', 'Obsidian Dagger']

Weapons = array('u',([Swords])

for i in Weapons:

    print(i)

Any idea what is going on?

4
  • The 'u' type code corresponds to Python’s obsolete unicode character. Why exactly are you trying to use the array datatype instead of a normal list? Commented Nov 21, 2018 at 1:13
  • @jk622 I was just trying to get comfortable working with arrays. Is there any difference between an array, and a list in python, or should I just use a list when I need an array? Commented Nov 21, 2018 at 1:48
  • In general, you should be using a list. Unless you are trying to use a particular function available to the array class, all you'd be doing is adding a constraint to the datatype of the objects inside it. Commented Nov 21, 2018 at 1:56
  • Ok, I did some additional reading, and makes sense when to use which. Why the type error for trying to place a list inside of an array though? This is what every tutorial I have watched has shown. Commented Nov 21, 2018 at 1:59

1 Answer 1

2

The 'u' type code corresponds to Python’s obsolete unicode character. This means it will work with unicode characters. You can test this

test_one = array("u", ["\u2641","\u2642","\u2643"])
for i in test_one:
    print(i)

You can also see it with this

test_two = array("u", ["T","e","s","t"])
for i in test_two:
    print(i)

Notice, in both cases it is a single character. Not entire strings. In order to do the string, you would have to convert each string to a list of characters.

test_three = array("u", [ch for ch in "Test"])
for i in test_three:
    print(i)

Lastly, if you want to break down the individual characters from a list of strings you can do a list comprehension similar to test_three or you can use a generator.

def character_generator(word_list):
    for word in word_list:
        for ch in word:
            yield ch

test_four = array("u", character_generator(["Test","One","Two"]))
for i in test_four:
    print(i)

At the end of the day though, the u typecode is for individual characters. Not strings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.