Retrieving the initial item from a nested list structure

To perform indexing, you can try the following approaches:
1. Solution 1:
Here is a rough way to achieve it:
Ideally, you should extract the search into a function that accepts the lists and the keyword.
2. Solution 2:
A possible solution is to use list slices.
Here is how you can implement it:
3. Solution 3:
Another approach is to extract two slices, one with the first element and one with the last, and then concatenate them.
The first index equal to “i” is represented by [‘X’, ‘X’, ‘X’] and x[0].
4. Solution 2:
You can use a combination of functions to remove the single quote characters around the string elements when you print.
5. Solution 3:
Here is a single liner solution for this.


Solution 1:

You’re on the right track. When your nested list is only one layer deep, you can use a list comprehension and -1 indexing to access both the first and last elements, just like you were attempting to do.

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

Output:

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


Solution 2:


Let’s explore the utilization of 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]]


Solution 3:

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


To avoid repetition, I take out two slices: one containing the first element and the other containing the last element. These slices are then concatenated. This method is effective even when the sublists have varying lengths.

Frequently Asked Questions