diff --git a/crates/polars-ops/src/chunked_array/list/namespace.rs b/crates/polars-ops/src/chunked_array/list/namespace.rs index fd6694d3f382..00bca56ec465 100644 --- a/crates/polars-ops/src/chunked_array/list/namespace.rs +++ b/crates/polars-ops/src/chunked_array/list/namespace.rs @@ -326,9 +326,12 @@ pub trait ListNameSpaceImpl: AsList { .downcast_iter() .map(|arr| sublist_get(arr, idx)) .collect::>(); - Series::try_from((ca.name(), chunks)) - .unwrap() - .cast(&ca.inner_dtype()) + // Safety: every element in list has dtype equal to its inner type + unsafe { + Series::try_from((ca.name(), chunks)) + .unwrap() + .cast_unchecked(&ca.inner_dtype()) + } } #[cfg(feature = "list_gather")] diff --git a/py-polars/tests/unit/namespaces/test_list.py b/py-polars/tests/unit/namespaces/test_list.py index 1e2a661d15d9..04733cbedb4c 100644 --- a/py-polars/tests/unit/namespaces/test_list.py +++ b/py-polars/tests/unit/namespaces/test_list.py @@ -69,6 +69,18 @@ def test_list_arr_get() -> None: ) == {"lists": [None, None, 4]} +def test_list_categorical_get() -> None: + df = pl.DataFrame( + { + "actions": pl.Series( + [["a", "b"], ["c"], [None], None], dtype=pl.List(pl.Categorical) + ), + } + ) + expected = pl.Series("actions", ["a", "c", None, None], dtype=pl.Categorical) + assert_series_equal(df["actions"].list.get(0), expected, categorical_as_str=True) + + def test_contains() -> None: a = pl.Series("a", [[1, 2, 3], [2, 5], [6, 7, 8, 9]]) out = a.list.contains(2)