# Finding index from a list for a list

I have a list containing one of four symbolic codes and would like to assign a number to each based on the index for each element in a second list "dictionary' containing one of each code.

typecode = Table[i, {i, 4}]

(* {1, 2, 3, 4} *)

typestrings = {"AA", "Aa", "aA", "aa"}

(* {"AA", "Aa", "aA", "aa"} *)

alist = RandomChoice[typestrings, 10]

(* {"Aa", "aa", "aa", "aa", "Aa", "aA", "AA", "AA", "aa", "aA"} *)

Table[Extract[
typecode ,
Flatten[Position[typestrings, alist[[i]] ]]
] , {i, 10 } ]

(* {2, 4, 4, 4, 2, 3, 1, 1, 4, 3} *)


works but feels awfully inelegant. Any suggestions?

• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Michael E2 Apr 30 '18 at 2:46

You can use an Association as dictionary:

typecode = Table[i, {i, 4}];
typestrings = {"AA", "Aa", "aA", "aa"};

RandomSeed[666];
alist = RandomChoice[typestrings, 10000];

a = Table[
Extract[typecode,
Flatten[Position[typestrings, alist[[i]]]]], {i,
Length[alist]}]; // AbsoluteTiming // First
b = Lookup[dictionary, alist]; // AbsoluteTiming // First
a == b


<|"AA" -> 1, "Aa" -> 2, "aA" -> 3, "aa" -> 4|>

0.043401

0.000695

True

As you can see, this is also much faster.

• Thanks so much. This is good. – jmm Apr 21 '18 at 14:18
• @jmm As a courtesy, remember to accept Henrik's answer if you choose it. – Alan Apr 21 '18 at 15:34
• @jmm You're welcome! – Henrik Schumacher Apr 22 '18 at 0:19
alist /. Thread[typestrings -> typecode]


{2, 4, 4, 4, 2, 3, 1, 1, 4, 3}