0

using string variable to create list variable names and get the length of each list

list1=[0,1,9,10]

list2=[2,3,11,12,13]

list3=[4,5,6,7,8]

list4=[16,17,25,26]

list5=[14,15,22,23]

nn=1

l='list'+str(nn) #the result of this concatenation is **List1**

#this should give me the length of List1 ;but it gives me length of bb variable bb=len(l)

print(bb)

AHMAD ZIA
  • 1
  • 1
  • don't use vairiables `list1`, `list2`, etc. but dictionary `data = {}` and `data[1] = [0,1,9,10]`, `data[2] = [2,3,11,12,13]`, etc. or nested list `data = [ [0,1,9,10], [2,3,11,12,13], ...]` And then you can get `len(data[nn])` – furas May 30 '20 at 17:52
  • I want to get the length of the Lists (list1...list19) therefore I am concatenating two variables l='list'+str(nn) which will result in 'list1' name of my first list then I will increase the number (nn variable) with the help of a loop nn+=1, to get name of my second list (list2), it works but when I want to get the len(l),it's supposed to give me the length of list1 which is 4, however it give me the length of string 'list1' which is 5 – AHMAD ZIA May 30 '20 at 18:33
  • in python you can't create variable name using `'list'+str(nn)` but you have structures `list` and `dictionary` to keep many elements and use number or string as key - ie.`data[nn]` – furas May 30 '20 at 18:48
  • BTW if you will keep all on list `data = [ [0,1,9,10], [2,3,11,12,13], ...]` then you don't need `nn` but `for item in data: print( len(item) )` – furas May 30 '20 at 19:06
  • BTW: example code https://pastebin.com/b5AZ92aT – furas May 30 '20 at 19:59

0 Answers0