'Double the size of a list of random integers, then sort and print it

Here, I have a list of random integers:

import random
list = [random.randint(0, 30) for x in range(6)]
pass

I want to double the size of this list, sort it, and print it. Here's what I've tried:

def list_doubled(list):
    doubled = []
    i = 0
    while i <= len(list):
        for item in list:
            doubled.append(list[i])
            doubled.append(list[i])
            i += 1
    print(doubled)

list_doubled(list)

This code is meant to only double the size of the list. When I run the program, I get "IndexError: list index out of range" with emphasis on lines 11 and 16.



Solution 1:[1]

Creating the list:

import random
numbers = [random.randint(0, 30) for x in range(6)]

Use extend to add the list to itself, in order to double it:

numbers.extend(numbers)   # or numbers += numbers

Or add as many random numbers as there are items in the list, if you need the additional numbers to also be random:

numbers.extend(random.randint(0, 30) for _ in range(len(numbers)))

use sort to sort it:

numbers.sort()

Use print to print it:

print(numbers)

Solution 2:[2]

Change your <= to < in your while loop line while i <= len(list):. You also might want to look at the comments, they have good advise on additional potential bugs you might encounter.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2