Python Forum
Very beginner but please help! - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Very beginner but please help! (/thread-11911.html)



Very beginner but please help! - thurpe - Jul-31-2018

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


RE: Very beginner but please help! - buran - Jul-31-2018

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


RE: Very beginner but please help! - thurpe - Jul-31-2018

I understand, thank you very much for the clarification!