Luís Lopes
Luís Lopes

Reputation: 85

Acessing last list element using list comprehension

Problem - Creat a list with variable size and acessing last element.

I have divided my problem in two functions. First function - I have done this first function using normal appending method and list comprehension; Second function - accessing last element

#first code
v = []

def creat_v():
  size = int(input('size  -'))
  for i in range(0,size):
    number = int(input('Number - '))
    v.append(number)
  return v
print(creat_v())

def last_element():
  return v[len(v)-1]
print(last_element())

#second code
v = []

def creat_v():
  v = [int(input('Number - ')) for i in range(0,int(input('Size - ')))]
  return v
print(creat_v())

def last_element():
  return v[len(v)-1]
print(last_element())

By doing the second code ('List comprehensions') it prints the list but returns the error regarding the second function:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    print(last_element())
  File "main.py", line 10, in last_element
    return v[len(v)-1]
IndexError: list index out of range

Upvotes: 1

Views: 65

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195653

Your code returns error, because in function:

def creat_v():
  v = [int(input('Number - ')) for i in range(0,int(input('Size - ')))]
  return v

you're assigning to local variable v, not changing global variable v.

You can add global v to this function or call this function like this: v = creat_v()


FULL CODE:

v = []

def creat_v():
  v = [int(input('Number - ')) for i in range(0,int(input('Size - ')))]
  return v

v = creat_v()
print(v)

def last_element():
  return v[len(v)-1]

print(last_element())

Upvotes: 4

Related Questions