How can I extract an integer from a 2D list in Python?
Asked by
MellowCedar47
My Python code produces a nested list containing one value, like output = [[23]], but I need to get the integer 23 itself. What is the correct way to extract that value?
Answers
It may be worth checking why the producing code returns `[[23]]` instead of `23`. Fixing the shape at the source is often cleaner than extracting the value afterward, especially if the output might sometimes be empty or contain multiple values.
Reply to this answer
You can also unpack the inner list: `value, = output[0]`. This works when the inner list contains exactly one element, and it makes that assumption explicit.
Reply to this answer
If the structure is always exactly a 2D list with one item, index into both levels: `WhatIWant = output[0][0]`. For `output = [[23]]`, this gives `23`.
Reply to this answer
If the nesting depth can vary, you could repeatedly take the first element until you reach a non-list value. For example: `def first_value(value):n while isinstance(value, list):n if not value:n return Nonen value = value[0]n return value`. This handles both `[[23]]` and `[[[23]]]`, but you should decide how empty lists or unexpected shapes should be handled.
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowCedar47: I understand why the code produces the nested list; I mainly wanted to know how to extract the integer from it.