[Tutor] Creating Lists

Steven D'Aprano steve at pearwood.info
Thu Nov 13 00:27:59 CET 2014

On Wed, Nov 12, 2014 at 04:27:33AM +0000, niyanaxx95 at gmail.com wrote:

> Create a list of 20 unique (no number appears twice) random integers with values
> between 1 and 45.

Here is how I would produce a list of 7 unique random integers with
values between 123 and 175. Lines starting with "py> " are code which I
have typed in the Python interactive interpreter. I don't type the py>
part, Python automatically shows that. The output then follows:

py> import random
py> random.sample(range(123, 176), 7)
[129, 151, 147, 137, 130, 153, 152]

Can you adjust that to do what you want?

> Print the list of random numbers with the header “Random list of 20
> numbers”.

This is how I would print a list of numbers with a header, separating
each number with a bunch of dots:

py> numbers = [2, 4, 8, 16]
py> print(*numbers, sep="......")
2......4......8......16

Note the asterisk * in front of numbers. What happens if you leave the
asterisk out? What happens if you leave the asterisk in, but remove the
"sep=" part?

> Find the largest number in the list. Remove the largest number from the list. Find the
> smallest number in the list. Remove the smallest number from the list.

Here is how I would find the largest and smallest numbers from a list:

py> numbers = [17, 11, 3, 99, 100, 41]
py> min(numbers)
3
py> max(numbers)
100

And here is how I would remove a number from a list:

py> print(numbers)  # Before
[17, 11, 3, 99, 100, 41]
py> numbers.remove(99)
py> print(numbers)  # And after.
[17, 11, 3, 100, 41]

> Print the length of the list with the header “The length of the list
> is: ” Print the list with the header “The list with the largest and
> smallest number removed: ”

Here is how I would find out the length of the list:

py> len(numbers)
5