-2

Is there any way how I can get every first/second/third/... Element of a two dimensional list, e.g. from the list

list = [[1,2], [3,4], [5, 6]]

Get the values 1,3,5 or is it only possible with a loop? Because a loop wouldn't be very practical if I want to do

If 2 in list:
...
petezurich
  • 9,280
  • 9
  • 43
  • 57
Tobi
  • 3
  • 1
  • Usually to navigate two dimensional lists you'll want to nest a series of loops to access the children elements as desired. For (all elements in list) For (all elements in each element) if (x then y).. – JakeofSpades Jan 13 '20 at 20:41
  • I can put it this way besides recursion (which technically is not a loop) you cannot do it without a loop – Lars Nielsen Jan 13 '20 at 20:41
  • Does this answer your question? [First items in inner list efficiently as possible](https://stackoverflow.com/questions/13084619/first-items-in-inner-list-efficiently-as-possible) – n00by0815 Jan 13 '20 at 20:58

3 Answers3

1

A list comprehension will work just fine. You index each element separately:

firsts = [x[0] for x in lst]  # [1,3,5]
seconds = [x[1] for x in lst]  # [2,4,6]
# etc

You can use the list comprehension in-line if desired:

if 2 in [x[1] for x in lst]:
    print("Found 2 in a sublist")
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Using a generator expression instead of a list comprehension in the condition would allow the condition to short-circuit when it finds the target element. The performance gain would be minimal for most reasonably-sized lists, but it's still worth noting. – jirassimok Jan 13 '20 at 20:54
  • 1
    The generator will use less memory, but could take *longer*, even with short-circuiting, since iterating over a generator is significantly slower than iterating over a list. `999 in list(range(1500))` is almost twice as fast as `999 in (x for x in range(1500))`, even considering the time it takes to build the list in the first place (37 microseconds per loop vs 65). – chepner Jan 13 '20 at 21:05
  • My own tests indicate that `x in list(range(n))` is faster than both `x in [i in range(n)]` and `x in (i in range(n))`, but the generator expression is faster than the list comprehension, regardless of whether or not the short-circuit occurs. However, if the short-circuit does not occur until about 70% of the way through (in my tests) and `data` is a pre-defined list, `x in [i for i in data]` is faster than `x in (i for i in data)`. The list comprehension will still take up more space, though that should matter less unless the lists are _very_ big. – jirassimok Jan 13 '20 at 21:55
1

You could use zip to transpose the list:

lst = [[1,2], [3,4], [5, 6]]
lst_transp = list(zip(*lst))

print(lst_transp)
# output: [(1, 3, 5), (2, 4, 6)]
Heike
  • 24,102
  • 2
  • 31
  • 45
0

You could use map

l = [[1,2], [3,4], [5, 6]]
result = map(lambda x: x[0], l)
print(list(result))
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
jdew
  • 11
  • 1
  • 2
  • 2