Sp_95
Sp_95

Reputation: 133

Extracting first and last element from sublists in nested list

How do you extract the first and last elements from each sublist in a nested list?

For example:

x=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(x)
#[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The desired result-

[[1, 3], [4, 6], [7, 9]]

This is the closest I've seen-

a = [x[i][i] for i in (0, -1)]
print(a)
#[1, 9]

Upvotes: 4

Views: 2641

Answers (6)

Sven Hendrikx
Sven Hendrikx

Reputation: 53

You can loop through the list and access them from there:

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

out = []
for arr in x:
    out.append([arr[0], arr[-1]])

print(out)

Output:

[[1, 3], [4, 6], [7, 9]]

Furthermore, you can use list comprehension:

out = [[arr[0], arr[-1]] for arr in x]

Upvotes: 0

I would recommend doing it like this. The list[-1] syntax is meant to get the last element in a list which is what you want.

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

for elem in x:
    print(elem[0], elem[-1])

This just prints them in a standard format but to put them back into a new list in this order would be simple.

Upvotes: 0

Red
Red

Reputation: 27547

Here is how you can use list slices:

x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = [l[::len(l)-1] for l in x]
print(x)

Output:

[[1, 3], [4, 6], [7, 9]]

Upvotes: 3

smwhr
smwhr

Reputation: 683

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

>>> [a[:1] + a[-1:] for a in x]
[[1, 3], [4, 6], [7, 9]]

I extract 2 slices, one with the first element, one with the last, and concatenate them.
It will works even when sublist are of different lengths.

Upvotes: 1

SALMAANYEHIA
SALMAANYEHIA

Reputation: 56

This works:


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

For your exact desired result, use this:


x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = []
for item in x:
    new_list.append([item[0], item[2]])

print(new_list)

Upvotes: 0

Derek O
Derek O

Reputation: 19555

You have the right idea. If your list inside list is only one layer deep, you can access the first and last elements with a list comprehension and -1 indexing like you were trying to do:

a = [[sublist[0],sublist[-1]] for sublist in x]

Output:

>>> a
[[1, 3], [4, 6], [7, 9]]

Upvotes: 11

Related Questions