Hi I'm a python beginner!

I'm trying to make a list of 3 numbers per line but I get an error. =(
Here's my code:

list2 = [23, 764, 12, 54, 83, 2, 543, 890, 1235, 453, 98] 

k = 0
while list2[k] != -1:
    first = str(list2[k])
    k = k + 1
    second = str(list2[k])
    k = k + 1
    third = str(list2[k])
    k = k + 1
    print first.ljust(3), second.ljust(3), third.ljust(3)
last = list2[-1]

Python Shell: the "-" represents spaces and for some reason the spaces aren't showing when I paste it here.

23-------764------12
54-------83--------2
543------890------1235

Traceback (most recent call last):
File "C:\Users\Me\Documents\blahh.py", line 9, in <module>
third = str(list2[k])
IndexError: list index out of rangeprint last.ljust(3)

Recommended Answers

All 4 Replies

Once k gets past the number of available elements in your list you will get an IndexError. You can put in series of if statements making sure that k does not exceed the length of your list, or simply trap the error to break out of the while loop:

list2 = [23, 764, 12, 54, 83, 2, 543, 890, 1235, 453, 98] width = 5 # experiment with this value k = 0 while True: try:
        print str(list2[k]).ljust(width),
        k = k + 1
        print str(list2[k]).ljust(width),
        k = k + 1
        print str(list2[k]).ljust(width),
        k = k + 1 except IndexError:
        break print last = list2[-1]

First
while list2[k] != -1:
will never exit because -1 is not in list2 so you will always exceed the limits of the loop. Generally, this is done with a for loop.

list2 = [23, 764, 12, 54, 83, 2, 543, 890, 1235, 453, 98] stop = len(list2) for k in range(0, stop, 3): ## step=3 for m in range(0,3): ## print 3 per line this_el = m+k ## k + 0-->2 = this element in list2 if this_el < stop: ## minus 5d=left justified
        print "%-5d " % (list2[this_el]), ## note the comma at the end print ## new line

You can use a while loop if you prefer

list2 = [23, 764, 12, 54, 83, 2, 543, 890, 1235, 453, 98] 
 
stop = len(list2)
ctr = 0
while ctr < stop:
   print "%-5d " % (list2[ctr]),
   ctr += 1
   if 0 == ctr % 3:   ## new line
      print 
print

Thank you bumsfeld and woooee!

I wasn't taught the "%-5d" part of the code you have provided but I came up with this in the end:

list2 = [23, 764, 12, 54, 83, 2, 543, 890, 1235, 453, 98] stop = len(list2) for k in range(0, stop, 3): for m in range(0,3):
        this_el= m + k
        if this_el< stop:
        slice= str(list2[this_el])
        print slice.ljust(5), print
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.