Aaron
Aaron

Reputation: 151

Displaying contents of a list in a "bar graph"

I am new to Python and I am trying to learn how to combine lists with for and while loops for an upcoming workshop at Uni. I am stumbling on one thing though:

Basically, I have numerical values stored in a list and I want to display it like this:

1  IIIII
2  II
3
4  III 
5  II

So that I's represent the number, i.e 3 = III

I tried this code (I had already established count as a list earlier in my code):

listIndex = 1
while listIndex < len(count):
    print(listIndex, " ", end='')
    for number in count[listIndex]:
        print("I", end='')
    print()
    listIndex += 1

But I get the following error:

1   Traceback (most recent call last):
File "/Volumes/USB/workshop7.py", line 145, in <module>
for number in count[index]:
TypeError: 'int' object is not iterable.

I don't see what I've done wrong, I looked up the error and I don't see why I cant iterate through that for loop?

The for loop should use the listIndex variable to go to the corresponding index in the list and retrieve the value, displaying it as a series of Is to correspond with the number stored there? Any help in understanding where I've gone wrong would be much appreciated. This is for assessment (5%) so if you could help my thinking rather than give me the answer, it would be much appreciated.

Upvotes: 2

Views: 174

Answers (3)

Nipun Batra
Nipun Batra

Reputation: 11377

  1. In Python lists are 0 indexed, so you should start list_index from 0
  2. Knowing the count, you don't need to loop to print 'I'. In Python you can simply do:

    print 'I'*count[list_index]

Upvotes: 0

Michał Niklas
Michał Niklas

Reputation: 54332

count[listIndex] is an int value, not list. You can use range() to make list, or even better you can use "string multiply", i.e. print('I' * count[listIndex]) and omit for loop.

Upvotes: 2

rmunn
rmunn

Reputation: 36708

So you have a list named "count" that contains counts, and you're fetching one of them with count[listIndex]. What's the result? An int, right?

That means that your for loop is trying to do something like:

for number in 3:
    print("I", end='')

Is "for number in 3" a valid way to do loops in Python? What would be a better way to write that for loop?

Upvotes: 1

Related Questions