Python Forum

Full Version: excercise python list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,I want you to help me with the solution of an exercise which is very difficult for me to simply tell me the solution in a very simple and understandable way and then try in a difficult way. the exercise is the following:::://Make a list of 20 places and fill them in red, green, blue in random order and then put them in the right order (based on this order :: red, green, blue);
Hello, we are not solving assignments for people here. Post your attempt - code in Python code tags and potential errors in error tags. It will also help to show the result/output you get and the result you want to have. From there we can help you correct the mistakes in code and guide you in the right direction.
my codec is:
import random
list=[]
colors=['red','green','blue']
for i in range(20):
    list.append(random.choice(colors))
print (list)
for i in range(20):
        if list[i]=="blue":
            list.insert(19,list.pop(i))
        if list[i]=="red":
            list.insert(0,list.pop(i))
print (list)
I would like to ask whether it is done in a simpler and easier way without many commands (for,if,while,)a simple way.
You can skip the whole second for loop if you just sort it:
list.sort(reverse=True)
with the function sort you can send me this solution based on the variable sort
It's built into the list type. There's nothing to send.

>>> help([].sort)
Help on built-in function sort:

sort(...) method of builtins.list instance
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
the right way but not the one I'm looking at can we do it with the command if i in.....I want to sort the colors in the order I gave some commands you wrote I do not know them yet (if,in,while,for,def)
Please can you try to make full sentence. English is not my mother language and currently I don't understand your question.

Do you want to have the order of appending? Then do nothing, task is finished. The order stays in a list.

If you need to sort the items in the list by name (A-Za-z), just use the in-place sort of list.
list1 = ['s', 'z', 'd', 'a']
list1.sort()
print(list1)
If you need the original list and a sorted list:
list1 = ['s', 'z', 'd', 'a']
list2 = sorted(list1)
print(list2)
If you need a custom order, you have to write your own key-function for sorted.
You can read here more: https://wiki.python.org/moin/HowTo/Sorting