About variables, evaluation and list creations
The following Python statements:
dog = 1
cat = 1
rose = 0
violet = 0
Will create variables named dog, cat, rose and violet with the values:
- 1 for the variable dog
- 1 for the variable cat
- 0 for the variable rose
- 0 for the variable violet
The type of all of these values are going to be integer (or int)
The following python statement:
List_of_things = [dog, cat, rose, violet]
Will create a variable called List_of_things and assign it the value of the expression in the right side of the = operator.
To assign the value of the expression in the right side of the = operator, it first has the evaluate the expression. The expression is the following:
[dog, cat, rose, violet]
This expression means, because of the [ and ] symbols, that you want a new list to be created from the values provided. But in our case the values provided are variables, which means they must be evaluated (in the case of a variable, converted to the value they hold) before they are provided as an item for the list to be created.
Therefore, the expression to be evaluated is equivalent to:
[1, 1, 0, 0]
And the list to be created won't store the information about which variables were used to create the list.
The expression then will be evaluated to the list object created from the provided values.
Solution with dict
One possible way of achieving the desired effect would be to use a dict to associate each possible string (value) to be printed to an integer.
integer_associated_to_string = {
"dog" : 1,
"cat" : 1,
"rose" : 0,
"violet" : 0
}
Then you could iterate over the entries of the dict and test for a condition:
for item in integer_associated_to_string:
if integer_associated_to_string[item] in [0,1]:
print(item)
Note in this case item will iterate over the key values of the dict (the values to the left of the : during the dict creation), and integer_associated_to_string[item] will evaluate to the value on the right of the : during the dict creation.
Solution with list of tuple
One limitation of the dict approach would be that dict keys must be unique, in this case a list of tuples would allow for repetition of string values in the list.
For example, for a new category associated with integer 2 meaning colors:
list_of_tuple = [
("dog", 1),
("cat", 1),
("rose", 0),
("violet", 0),
("violet", 2)
]
violet could also be a color (category 2), and dict wouldn't allow for this association.
To iterate in this case:
for item in list_of_tuple:
if item[1] in [1,2]:
print(item[0])
Here item[1] means the integer category and item[0] means the string itself.