How to write a function which needs to access the first value which is not a list from an arbitray-deep nested list? Sometimes right syntax will be somelist[0], some other time somelist[0][0] etc. Is flattening of the whole list just to read the first one correct solution?
Asked
Active
Viewed 39 times
0
Reloader
- 742
- 11
- 22
3 Answers
0
This has been answered here.
Summarizing:
from itertools import chain
myList = [ [1, 2, 3], [5, 6], [], [114, 66, 55] ]
flatList = list( chain( *myList ) )
Output: [1, 2, 3, 5, 6, 114, 66, 55]
Then just access flatList[0] for the first element.
Community
- 1
- 1
Tejas Pendse
- 551
- 6
- 19
0
I would do something like
value = my_list[0]
if isinstance(value, list):
value = value[0]
# use the value
mpcabd
- 1,813
- 15
- 20
0
Try this:
def get_first_item(value):
if isinstance(value, list):
return get_first_item(value[0])
return value
fred.yu
- 865
- 7
- 10