-3

I want to create sublist based on looping, but still not find the logic on how to do it?

''' source list'''
list = [1,2,3,4,5,6,7,8,9]
''' sublist goals'''
list_1 = [1,4,7]
list_2 = [2,5,8]
list_3 = [3,6,9]
MuflihHD
  • 13
  • 3
  • 3
    What have you tried? A simple for-loop perhaps? – meowgoesthedog Apr 29 '19 at 15:27
  • Can you explain what logic you are wanting to use? It appears as though you are splitting on every third item. – MyNameIsCaleb Apr 29 '19 at 15:27
  • You almost never need to create N independent variables whose names only differ by a digit. Try using a list of lists instead: `x = [[1,4,7], [2,5,8], [3,6,9]]`. If you're thinking "yes, that's what I wanted in the first place, but how do I get `x` given `list`?", consult [How do you split a list into evenly sized chunks?](https://stackoverflow.com/q/312443/953482) – Kevin Apr 29 '19 at 15:49

4 Answers4

0
list = [1,2,3,4,5,6,7,8,9]

list_1 = []
list_2 = []
list_3 = []

for j in range(1,4):
    for i in range(j,len(list)+1,3):
        if j == 1:
            list_1.append(i)
        if j == 2:
            list_2.append(i)
        if j == 3:
            list_3.append(i)

print (list_1)
print (list_2)
print (list_3)

output:

[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
ncica
  • 7,015
  • 1
  • 15
  • 37
0

Just create a 3x3 list and then append items to the list according to the condition

li = [1,2,3,4,5,6,7,8,9]

#Create a 3x3 list
res = [ [] for _ in range(3)]

for idx in range(len(li)):
    #Append elements accordingly
    index = int(idx%3)
    res[index].append(li[idx])

print(res)

The output will look like

[[1, 4, 7], 
[2, 5, 8], 
[3, 6, 9]]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

In addition to what others have posted you could create a dictionary with the name of the list as the key and the list as the values like this:

>>> for i in range(3):
...   d["list_{}".format(i)] = [list[i], list[i+3], list[i+6]]
... 
>>> d
{'list_2': [3, 6, 9], 'list_1': [2, 5, 8], 'list_0': [1, 4, 7]}```

scon
  • 9
  • 1
0

Did any one consider this?

>>> list=[1,2,3,4,5,6,7,8,9]
>>> list_1 = list[0::3]
>>> list_2 = list[1::3]
>>> list_3 = list[2::3]
>>> list_1
[1, 4, 7]
>>> list_2
[2, 5, 8]
>>> list_3
[3, 6, 9]

A loop would look like this

for i in range(0,3):
    list_i = list[i::3]
    print(list_i)
dave
  • 76
  • 5