I have the following list named "rows":
[['1', 'Peter', 'Cookies'], ['2', 'Sarah', 'Chocolate'], ['3', 'Daria', 'Lollies']]
I'm trying to store the elements at index 0 within each list in a variable called ID with set comprehension but am struggling.
I've tried the following:
ID = {[row[0] for row in rows]}
but get the error:
unhashable type list
I need to find a solution by using list comprehension.
CodePudding user response:
THe error : unhashable type list is because you are trying to use a list as a key in a dictionary. Try this to get the first element of each list.
ID = [row[0] for row in rows]
# ['1', '2', '3']
CodePudding user response:
CODE:
import numpy as np
rows = [['1', 'Peter', 'Cookies'], ['2', 'Sarah', 'Chocolate'], ['3', 'Daria', 'Lollies']]
ID = [rows[row][0] for row in range(len(rows))]
ID
OUTPUT:
['1', '2', '3']