Solved: Search for a symmetrical inner elements of a list python

The main problem is that Python does not have a built-in function to find the symmetrical inner elements of a list.


I have a list of lists and I want to find the symmetrical inner elements. For example:
<code>lst = [[1,2,3], [4,5,6], [7,8,9]]
</code>
The output should be: <code>[2]</code> because it is the only symmetrical element in the list.


A:

You can use a nested list comprehension with <code>all()</code>: 
<code>[x for l in lst for x in l if all(l[i] == l[-i-1] for i in range(len(l)//2))] # [2] 
</code>

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

[x for l in lst for x in l if all(l[i] == l[-i-1] for i in range(len(l)//2))] # [2]

Elementos of a list

In Python, a list is a data structure that stores a collection of items. Each item in a list is represented by an object of type list.

Related posts:

Leave a Comment