Python Forum
Very beginner but please help!
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Very beginner but please help!
#1
Hi, I am following a set of exercises, and I got stuck a bit on this one:
Write a function that returns the first and last elements of a list.

My code worked when the list was set, but when I use randomly created list, the command returns the whole list twice.
import random


def listing():
    list = [random.sample(range(1,100),10)]
    return [list[0], list[-1]]

print(listing())
Can you please check?:)

thurpe
Reply
#2
random.sample returns list. But you put this in square brackets, so it becomes list of lists with one element,e .g.
[[93, 15, 58, 11, 35, 67, 36, 33, 42, 63]]
you can easily check this if print it immediately after line 5.

import random
 
 
def listing():
    lst = random.sample(range(1,100),10)
    return [lst[0], lst[-1]]
 
print(listing())
Also, don't use list as variable name. list() is built-in function and using list as a variable name the function is no longer available
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
I understand, thank you very much for the clarification!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020