user3211582
user3211582

Reputation: 9

Python - step through list -TypeError: 'int' object is not iterable

Trying to learn python, I am trying to do:

list0=['A','B'];
list1=['C','D'];
z=0
while z < 2:
    for q in list(z):
        print q
    z += 1

I would like it to print

A
B
C
D

but i get the following error:

Traceback (most recent call last):
  File "main.py", line 6, in 
    for q in list(z):
TypeError: 'int' object is not iterable

Is this possible in python? I know I have done this or something similar in other languages.

Upvotes: 0

Views: 9336

Answers (5)

Nafiul Islam
Nafiul Islam

Reputation: 82470

First of all, you do not need to use semicolons in Python if you have only 1 statement per line. So in your code sample:

list0=['A','B'];
list1=['C','D'];

Should be just:

list0=['A','B']
list1=['C','D']

Note that your syntax is correct, but there is no need for those two tailing semicolons. If you wanted to declare both lists on the same line then you would use a semicolon:

list0=['A','B']; list1=['C','D']

However, this is not advised.

Secondly, in your code, there is no need to have a separate counter, z, you can simple glue the lists together, and then just print them:

for letter in list0 + list1:
    print letter

As a demonstration:

>>> list0=['A','B']; list1=['C','D']
>>> for letter in list0 + list1:
>>>     print letter
...     
A
B
C
D

Now let me explain the error that you got:

'int' object is not iterable

When you want to make a list in python you need to give the constructor an iterable object (an object that you can loop through, like an array), when you give it a simple number, it will give you an error, so you can create a list like so:

>>> var = list([1,2,3,4])
>>> type(var)
<type 'list'>

But you don't even need to do that, you can just put things in []s and that will creat ea list for you too:

>>> var2 = [1,2,3,4]
>>> type(var2)
<type 'list'>

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54183

The point I don't think anyone has touched upon is that list is a built-in Method in Python. If you did list("abcdefg"), you would get out ['a','b','c','d','e','f','g'] -- a list of all the elements in the iterable you pass into list. So when you do for q in list(z) I know you're trying to do for q in list1 and for q in list2, but instead you're doing for q in list(1) which is trying to iterate over the number 1 -- that's not possible, and it's why you're getting the TypeError.

If you're DEADSET on using this particular implementation (and trust me, you really should make a list of lists as the other answers have suggested), do instead:

list0 = ["A","B"]
list1 = ["C","D"]
for i in range(2): #which is a generator that yields 0 and 1
    for q in vars()["list{}".format(i)]:
        print(q)

vars() is a built-in function that returns a dictionary, the keys of which are all the locally-available variables as strings, the values of which are the values stored in those variables. Now instead of calling the built-in method list on a number, you're using string formatting to build a string that corresponds to the lists you're using.

That said, anytime you're trying to use your variable name to contain data, you're really just hacking together code. Try to weave it more elegantly than relying on your code to generate variable names to iterate through :)

For completeness, here is what you SHOULD do!

a_list = ["A","B"]
b_list = ["C","D"]
lists = a_list+b_list #lists == ["A","B","C","D"]
# could also do lists = [element for element in list_ for list_ in [a_list,b_list]]
# but why in the heck should we complicate things?? May be useful if you need to
# filter elements for whatever reason. Maybe only uppercase letters make it through?
# so something like:
# c_list = ["e","F"]
# lists = [e for e in list_ for list_ in [a_list,b_list,c_list] if e.isupper()]
# I dunno, just throwing it out there for your bag of tricks!
for item in lists:
    print(item)

Alternatively if you have a TON of iterable items, not necessarily just lists that support a concatenation operator,

list0 = ["A","B"]
...
list99 = ["Y","Z"]

lists = [list0, ... , list99]
for iterable in list:
    for element in iterable:
        print(element)

Upvotes: 0

volcano
volcano

Reputation: 3582

list requires an iterable as an argument. You called it on integer

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239463

  1. You can gather both the lists as another list and then you can index it like this

    list0=['A','B']           # We don't need semicolons
    list1=['C','D']
    lists=[list0, list1]      # Create a list of lists
    z=0
    while z < 2:
        for q in lists[z]:    # We access list's index with [], not with ()
            print q
        z += 1
    

    Output

    A
    B
    C
    D
    
  2. The same effect can be achieved like this

    for current_list in [list0, list1]:
        for current_item in current_list:
            print current_item
    
  3. There is a builtin python module, which comes with a itertools.chain method, which can be used like this

    import itertools
    for current_item in itertools.chain(list0, list1):
        print current_item
    

Upvotes: 3

Christian Tapia
Christian Tapia

Reputation: 34146

The most similar think from what you tried to do is create a list composed by the 2 lists you have. So you can access each list by an index (0 or 1) in the form lists[index]

lists = [['A', 'B'], ['C', 'D']]
z = 0
while z < 2:
    for q in lists[z]:
        print q
    z += 1

Note that list is not a good name for a variable since it hides the list type from Python.

Upvotes: 1

Related Questions