2

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))
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
Luismaia1994
  • 143
  • 1
  • 8

3 Answers3

3

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)]
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • the thing i dont understand is in what point you are telling you want to append? you simply wrote v[j] for j in range(len(V),-1,-1). That will invert the list but imagine i want to append some other values where does the append enter in list comprehension? – Luismaia1994 May 06 '19 at 13:10
  • 1
    There is no appending in list comprehension. list comprehension creates a new list with items that are iterating inside. – Mehrdad Pedramfar May 06 '19 at 13:12
1

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
Tom Ron
  • 5,906
  • 3
  • 22
  • 38
1

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))
molbdnilo
  • 64,751
  • 3
  • 43
  • 82