Ibe
Ibe

Reputation: 6035

How to call lists in a for loop?

I am stuck at a failry simple looping exercise through lists and getting error "TypeError: 'list' object is not callable". I have three lists with n number of records. I want to write first record from all lists in the same line and want to repeat this procedure for n number of records, it will result in n number of lines. Following are lists that I want to use:

lst1 = ['1','2','4','5','3']
lst2 = ['3','4','3','4','3']
lst3 = ['0.52','0.91','0.18','0.42','0.21']

istring=""
lst=0
for i in range(0,10): # range is simply upper limit of number of records in lists
    entry = lst1(lst)
    istring = istring + entry.rjust(11) # first entry from each list will be cat here
    lst=lst+1

Any startup would be really helpful.

Upvotes: 1

Views: 591

Answers (3)

dansalmo
dansalmo

Reputation: 11686

This works for any size of lists:

for i in zip(lst1, lst2, lst3):
    for j in i:
        print j.rjust(11),
    print

          1           3        0.52
          2           4        0.91
          4           3        0.18
          5           4        0.42
          3           3        0.21

Upvotes: 3

user849425
user849425

Reputation:

>>> lst1 = ['1','2','4','5','3']
>>> lst2 = ['3','4','3','4','3']
>>> lst3 = ['0.52','0.91','0.18','0.42','0.21']
>>> a = zip(lst1, lst2, lst3)
>>> istring = ""
>>> for entry in a:
...     istring += entry[0].rjust(11)
...     istring += entry[1].rjust(11)
...     istring += entry[2].rjust(11) + "\n"
... 
>>> print istring
          1          3       0.52
          2          4       0.91
          4          3       0.18
          5          4       0.42
          3          3       0.21

Upvotes: 2

Paul
Paul

Reputation: 27433

Try entry = lst1[lst] instead of entry = lst1(lst)

() usually denotes calling a function, whereas

[] usually denotes accessing an element of something.

A list is not a function.

Also, while you can keep your own index, a for loop makes this unnecessary

x = [1,2,3,4,5,7,9,11,13,15]
y = [2,4,6,8,10,12,14,16,18,20]
z = [3,4,5,6,7,8,9,10,11,12]
for i in range(0,10):
   print x[i], y[i], z[i]

1 2 3
2 4 4
3 6 5
4 8 6
5 10 7
7 12 8
9 14 9
11 16 10
13 18 11
15 20 12

Upvotes: 1

Related Questions