# Can I get element Id from nested list?

Hi, I would like to get the Id of elements in nested list

So far, I can get Id of elements in normal list, but not success in nested list

is there any way to achieve that?

@hctungBHP7B You need 2 for loops instead of 1. Try this:

Using list comprehension

``````toNestList = lambda x: x if any(isinstance(i, list) for i in x) else [x]
OUT = [[ele.Id for ele in eleList] for eleList in toNestList(IN[0])]
``````

OR

Using nested for loop

``````toNestList = lambda x: x if any(isinstance(i, list) for i in x) else [x]
OUT = []
for eleList in toNestList(IN[0]):
ids = []
for ele in eleList:
ids.append(ele.Id)
OUT.append(ids)
``````
4 Likes

But I have some question want to ask.
why does your code can deal with both normal list and nested list well.
Is the key at first line in your code?
Could you explain a little bit??

Thanks so much

1 Like

Yes, you guessed it right. The 1st line of code makes sure that the list (x) we are inputting is a nested list. If itâ€™s not a nested list then it will make it one by using `[x]`.

Check this out for more info: Python check if a list is nested or not - Stack Overflow

3 Likes

@AmolShah Thank you so much for your information !

1 Like

Hi @AmolShah
I also want to ask that why you can move the â€śIN[0]â€ť to last part?

I am trying rewrite your code, so I move the â€śIN[0]â€ť to beginning in order to figure out, but it showed error, I canâ€™t figure out the process of your code

is it about to the function of lambda??

@hctungBHP7B Itâ€™s difficult to explain but you cannot use it like what you have done.
Itâ€™s called a lambda function if you want to know more about it.

You can try something as shown below if you want to ditch the concept of lambda functions for now.

``````if any(isinstance(i,list) for i in IN[0]):
toNestList = IN[0]
else:
toNestList = [IN[0]]

OUT = [[ele.Id for ele in eleList] for eleList in toNestList]
``````

OR

``````toNestList = IN[0]
if not any(isinstance(i,list) for i in toNestList):
toNestList = [toNestList]

OUT = [[ele.Id for ele in eleList] for eleList in toNestList]
``````
2 Likes