0

So I was trying some things out and then I found a problem with my code. I am trying to get the user to select a list and then iterate something for the number of items in that list.

I have simplified it here but you can still see the problem.

list1 = [0,1,0,1,0,1]
list2 = [1,0,1,0,1,0]

a = input("Which list do you want to search for?")
for item in range(len(a)):
    print(item)

This outputs the following:

Which list do you want to search for?list1
0
1
2
3
4
>>> 

You can see this code does not iterate the number of times I want it to. I was wondering if anyone could explain why this is or help me find a solution?

2
  • 4
    a is a number or a string, not the name of your variable Commented Dec 10, 2015 at 21:37
  • See what happens when you use print(a) Commented Dec 10, 2015 at 21:40

2 Answers 2

2

When you get user input into a, it is a string. When you are iterating through it in your example; you are iterating through the actual string 'list1'.

If you wanted to go through the items in the list you need to link them somehow.

Try this:

lists = {
'list1': [0,1,0,1,0,1],
'list2': [1,0,1,0,1,0]}

a = input("Which list do you want to search for?")
if a in lists:
    for item in lists[a]:
        print(item)
else:
    print("Don't have that list")

Note:

for item in lists[a]

That lists[a] references that list; you can do what you want with it now; like use range/len....

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

Comments

2

In case you are using Python3 (you must be, otherwise the code works fine),

a is a string, not the variable itself.

You can verify it doing

list1 = [0,1,0,1,0,1]
list2 = [1,0,1,0,1,0]
a = input("Which list do you want to search for?")
print(type(a))

which gives you

<class 'str'>

So you can try this instead:

for item in range(len(vars()[a])):
    print(item)

which produces

0
1
2
3
4
5

From the official docs:

vars([object])

Return the dict attribute for a module, class, instance, or any other object with a dict attribute. Objects such as modules and instances have an updateable dict attribute; however, other objects may have write restrictions on their dict attributes (for example, classes use a dictproxy to prevent direct dictionary updates). Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

As an alternative, you can use eval

for item in range(len(eval(a))):
    print(item)

but it's not recommended (see the official docs) since

This function can also be used to execute arbitrary code

Note: there are several ways to solve this problem. For example, as pointed out below, you could decide which list to use by checking the input with an if and hard-code the list in either branch taken. The problem with this option is that it does not fit a higher/variable/dynamic number of lists.

Another approach could be to store the lists in a dictionary and look them up using the input key, as suggested in another answer. This one and mine have the benefit of being able to handle any number of lists, not just a few and even lists created dynamically in the namespace.

6 Comments

a is the variable if he's using Python 2.x
@AbuAshrafMasnun thank you for your exact comment. However, had the OP used Python2.x, he'd not have posted the question, since the code would have worked correctly.
This seems excessively complex for someone who is just learning python. "Return the dict attribute for a module..." hmmmm . And eval is equally confusing. How about an if statement or manual lookup in a dictionary? Could you show the simpler alternatives? There is also know clear way to error check either of these solutions for simple input typos
@en_Knight Yes, there are many possible ways to solve the problem. Feel free to add your answer.
@Pynchia fair enough; I know it's not your job to address all possible answers, I just mean that it seems surprising to have a moderately complicated answer when it there may be considerably simpler ones. Is there a particular reason you recommend these two styles?
|

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.