1

This is what I have:

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

for i in mylist1:
    if i[0] % 2 == 0:
        print(i[0])
    if i[1] % 2 == 0:
        print(i[1])
    if i[2] % 2 == 0:
        print(i[2])

Is there a shorter way?

Josh Karpel
  • 2,110
  • 2
  • 10
  • 21
Jay Alli
  • 49
  • 6
  • 1
    Possible duplicate of [How to make a flat list out of list of lists](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) ... and [Flattening a shallow list in Python (duplicate)](https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) – wwii Jun 22 '19 at 03:19

6 Answers6

1

List comprehension?

print('\n'.join(str(i) for sublist in mylist1 for i in sublist if i % 2 == 0))

Less hardcore list comprehension?

for sublist in mylist1:
    print('\n'.join(i for i in sublist if i % 2 == 0))

For loop?

for sublist in mylist1:
    for i in sublist:
        if i % 2 == 0:
            print(i)
APerson
  • 8,140
  • 8
  • 35
  • 49
1

You can use filter with itertools' chain.from_iterable:

from itertools import chain
mylist1 = [[1,2,3], [4,5,6], [7,8,9]]   

print(list(filter(lambda x: x % 2 == 0, chain.from_iterable(mylist1))))

# [2, 4, 6, 8]
Mark
  • 90,562
  • 7
  • 108
  • 148
0

You can use a nested loop try this.

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

for i in mylist1:
    for j in i:
        if j % 2 == 0:
            print(j)
Diego
  • 216
  • 1
  • 11
0

If you know the format is going to be a list of lists, I suppose you could just use nested for loops

mylist1 = [[1,2,3], [4,5,6], [7,8,9]]  
for x in mylist1:
    for y in x:
        if y%2 == 0:
            print(y)

Unless you're asking it to be quicker in terms of CPU time in which case I would probably use numpy. Keep experimenting bud!

Tclack88
  • 21
  • 5
0

You can just pass *param to chain :

from itertools import chain
[i for i in chain(*mylist1) if i % 2 == 0]
LiuXiMin
  • 1,225
  • 8
  • 17
0

Yet another option, a one-liner that uses no imports:

print(*[val for lst in mylist1 for val in filter(lambda x: x & 1 == 0, lst)])

Or if having them on separate lines is important:

print(*[val for lst in mylist1 for val in filter(lambda x: x & 1 == 0, lst)], sep = "\n")
Gene
  • 46,253
  • 4
  • 58
  • 96