-1

My college assignment so far looks like this:

data = [[1,2,3], [4,5,6], [7,8,9]]
cout = [[]]*3
for i in range(len(data)):
    for j in range(len(data[i])):
        check = data[i][j]
        print(check)
        if data[i][j] % 2 == 0:
            cout[i].append(data[i][j])      

print(cout)

and its output was

[[2, 4, 6, 8], [2, 4, 6, 8], [2, 4, 6, 8]]

but i want it to be

[[2], [4, 6], [8]]

thanks in advance

Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75
Vesera
  • 17
  • 5

5 Answers5

2

It seems you want to extract the even items from your 2D list. There are many ways to do this

Using 2 for..in loops

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

for block in data:
    tmp = []
    for x in block:
        if x % 2 == 0:
            tmp.append(x)
    even.append(tmp)

Using lambda functions

data = [[1,2,3], [4,5,6], [7,8,9]]
even = [list(filter(lambda x: x % 2 == 0, l)) for l in data]

Output

[[2], [4, 6], [8]]
molamk
  • 4,076
  • 1
  • 13
  • 22
1

Hi welcome to Stackoverflow.

Change your initialization for cout to

cout = [[],[],[]]

Besides here some code how to debug your code

data = [[1,2,3], [4,5,6], [7,8,9]]
cout = [[],[],[]]
for i in range(len(data)):
    for j in range(len(data[i])):
        check = data[i][j]
        print("i =", i)
        print("j =",j)
        print(check)
        print(cout)
        if data[i][j] % 2 == 0:
            cout[i].append(check)      

print(cout)
ohlr
  • 1,839
  • 1
  • 13
  • 29
1

The problem is in the line cout = [[]] * 3. This is not creating three separate lists but 3 objects referencing to the same list. One way to fix this is to write cout = [[], [], []] or cout = [[] for _ in range(3)].

Check the other answers for cleaner way of achieving what you are trying to achieve, though.

norok2
  • 25,683
  • 4
  • 73
  • 99
  • 1
    thank you for this info, i just learned python and pretty much innocent at this language. when i searched how to create an empty nested list, i found it to be written like this. so, giving this info really helped me. thanks – Vesera Feb 24 '19 at 13:13
1

Another oneliner:

my_lists =  [[1,2,3], [4,5,6], [7,8,9]]
[l[(i+1)%2::2] for i, l in enumerate(my_lists)]
[[2], [4, 6], [8]]
Chris
  • 29,127
  • 3
  • 28
  • 51
1

To filter out uneven numbers from sublists in a list you can use nested listcomps:

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

[[i for i in l if not i % 2] for l in data]
# [[2], [4, 6], [8]]
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73