简体   繁体   中英

Python - TypeError: Unhashable type list error

I'm trying to create a comprehension that takes each value n in a list and returns the values from 1-n. IE for [1,2,4] the return should be [[1],[1,2],[1,2,3,4]] . My code is getting this unhashable type list error.

 {range(x) for x in {1,2,4}}

Braces - {} creates a Set of the element you pass to it. To create a list, you need to use brackets - []

[range(x) for x in [1,2,4]]

And to get the required output, you need to change your range() a little bit. range(2) will give you [0, 1] instead of [1, 2] .

You can use:

>>> [range(1, x+1) for x in [1, 2, 4]]
[[1], [1, 2], [1, 2, 3, 4]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM