Reputation: 143
I'm trying to solve a problem I already solved before but now using list comprehensions. The problem is simple I have a list and I want to invert it using list comprehension
Defining the first list was easy but when I append the inverted list it gives me the error in the title. I know we should not append in list comprehensions but I don't know what to put.
v=[]
p=[]
def listt():
v=[int(input('Digit element\n'))for j in range(0,int(input('Digit number of elements')))]
return v
print(listt())
def invert_list(v):
p=[p.append(v[j]) for j in range(len(v),-1,-1)]
return p
print(invert_list(v))
Upvotes: 2
Views: 263
Reputation: 66441
p
is a local variable; you can't append to it before it exists.
It's not clear why you want the global variables p
and v
(note that listt
does not modify the global v
).
def listt():
return [int(input('Digit element\n'))for j in range(0,int(input('Digit number of elements')))]
def invert_list(v):
return [v[j] for j in range(len(v)-1,-1,-1)]
x = listt()
print(x)
print(invert_list(x))
Upvotes: 1
Reputation: 11083
Try this instead of p=[p.append(v[j]) for j in range(len(v),-1,-1)]
:
p=[v[j] for j in range(len(v),-1,-1)]
Upvotes: 3
Reputation: 6181
When you are doing -
p=[p.append(v[j]) for j in range(len(v),-1,-1)]
p
does not exist, hence the error.
You can do the following -
def invert_list(v):
p = []
for j in range(len(v)-1,-1,-1):
p.append(v[j])
return p
Upvotes: 1