User inputs and sorted lists in Python 3

sort list python 3
python sorted lambda
python sorted key=lambda
python sort list of objects
python sort list of strings
python list sort by length descending
python sort vs sorted
how to input a list in python 3

I need help producing an output like this:

1. Enter a member: samantha 
Names: ['Samantha']
2. Enter a member: susan 
Names: ['Samantha', 'Susan']
3. Enter a member: billy 
Names: ['Billy', 'Samantha', 'Susan']
4. Enter a member: billy
4. Enter a member: samantha
4. Enter a member: Jason 
Names: ['Billy', 'Jason', 'Samantha', 'Susan']
5. Enter a member: 

Members:
1. Billy
2. Jason
3. Samantha
4. Susan

I've made an effort to create a program which does this, but to no avail. I will be commenting in my questions in the code itself. Thanks in advance for the help.

def function():

    x = []
    #a = "1." # I tried to number the questions by adding these but it doesnt work
    while True:
        #a += 1
        name = input("Enter name: ").title()
        x.append(name)

        print("Names:", x)
        #if name == name: # this condition is made so that an input that is typed in again doesn't get included in the list
            #name = input("Enter name: ").title()

            # where should I add an insert() here to have the list alphabetically ordered?

        if not name: # pressing enter prints out the second half of the output, listing the members
            #print("\nMembers:", x).sort()
            break

function()

You did almost everything correct but the problem is where you are breaking from the loop. You are first appending the name and then checking if the input was just an enter. So, first check the input and then append it to list. Here is my code:

def fun1():
    l = []
    while True:
        s = input("Enter a member: ")
        if not s:
            break
        l.append(s.title())
        print("Names:", l)
    l.sort()
    print("Members:")
    for i in range(0, len(l)):
        print(i+1,end = '')
        print(".", l[i])
fun1()

Hope it helps.

How to Use sorted() and sort() in Python – Real Python, Also, this tutorial uses Python 3, so example output in this tutorial might vary You can use Python to sort a list by using sorted() . Notice how even though the input was a set and a tuple, the output is a list because sorted()  Python 3’s sorted() does not have a cmp parameter. Instead, only key is used to introduce custom sorting logic. key and reverse must be passed as keyword arguments, unlike in Python 2, where they could be passed as positional arguments. If you need to convert a Python 2 cmp function to a key function,

Sorting HOW TO, There is also a sorted() built-in function that builds a new sorted list from an iterable. a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5] that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record. Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Talent Hire technical talent

You don't need many changes to your code. Main restructuring involves to move all exceptions like repetition of names and no input to the top of the loop. More explanations are integrated in the comments.

def function():
    x = []
    #no need to keep track of the number of members, the list length will give us this information
    #infinite loop that will be interrupted, when no input is given 
    while True:
        #determine length of list, +1 because Python index starts with 0
        n = len(x) + 1
        #ask for input, format prints the number into the bracket position
        name = input("{}. Enter a member: ".format(n))
        #check if name already in list
        if name in x:
            #if name in list, ignore the input and start while loop again
            continue
        #no input - print out members and stop
        if not name: 
            print("Members:")
            #get for each member the index number i
            for i, member in enumerate(x):
                #print index in position {0} and member name in position {1}
                print("{0}. {1}".format(i + 1, member))
            #leave function()
            return
        #append name and sort list
        x.append(name)
        x.sort()        
        #print list
        print("Names:", x)


function()

Python, In this article, we will see how to get as input a list from the user. Examples: Input : n = 4, ele = 1 2 3 4 Output : [1, 2, 3, 4] Input : n = 6, ele = 3 4 1 7 9 6 Output : [3,  List comprehension is an elegant way to define and create list in Python. We can create lists just like mathematical statements in one line only. It is also used in getting multiple inputs from a user.

I'd personally prefer to use a set to avoid duplicates in a cleaner manner, and I'd also consolidate the two printing sections into a separate function. So my suggestion is for the following, which acts a bit differently from yours, but is (in my opinion) simpler:

def print_members(members):
    numbered_members = enumerate(sorted(members), 1)
    print("Members:", ", ".join(
        "{}. {}".format(*tup) for tup in numbered_members))


def collect_members():
    members = set()
    while True:
        next_member_num = len(members) + 1
        name = input("{}. Enter a member: ".format(next_member_num)).title()
        if name:
            members.add(name)
            print_members(members)
        else:
            print_members(members)
            return

Note that the sorting (only needed here for the print_members function) will become very expensive if the number of members grows too much, and in that case I'd suggest using a binary search tree instead of a set.

Sorted() function in Python, JSON file using Python · Difference between input() and raw_input() functions in Python Sorting any sequence is very easy in Python using built-in method sorted() Output : Sorted List returned : [1, 2, 3, 4, 6, 7, 8] Reverse sort : [8, 7, 6, 4​, 3, 2, Key also takes user-defined functions as its value for the basis of sorting. Python | Get a list as input from user We often encounter a situation when we need to take number/string as input from user. In this article, we will see how to get as input a list from the user.

I kept much of your structure, but fixed quite a few things. To get the numbering, I used the % string formatting operator. You could also use str.format, which many seem to prefer.

You can sort a list in place (the list is replaced with the sorted list) by using x.sort(). To check if something is/is not in a list use thing is in mylist or thing is not in mylist

def function():

    x = []
    a = 1
    while True:
        prompt = '%d. Enter a member: ' % a
        name = input(prompt)
        name = name.title() # convert first letter to uppercase

        if name.strip() == '':  # enter or empty string entered
            print()
            print('Members:')
            for idx, item in enumerate(x):
                print('%d. %s' % (idx+1, item))
            break
        elif name not in x:
            x.append(name)
            x.sort()  # sort x in place
            print("Names: ", x)
            a += 1


function()

and my output:

1. Enter a member: samantha
Names:  ['Samantha']
2. Enter a member: susan
Names:  ['Samantha', 'Susan']
3. Enter a member: billy
Names:  ['Billy', 'Samantha', 'Susan']
4. Enter a member: Jason
Names:  ['Billy', 'Jason', 'Samantha', 'Susan']
5. Enter a member:

Members:
1. Billy
2. Jason
3. Samantha
4. Susan


------------------
(program exited with code: 0)

Press any key to continue . . .

Python Sorting | Python Education, The easiest way to sort is with the sorted(list) function, which takes a It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of The sorted() function seems easier to use compared to sort(), so I a list of 3-d coordinates, the natural python representation would be  Sorting the list is as easy as calling the sort() function. After the example calls the sort() function, it prints the list again so that you can see the result. Choose Run→Run Module. You see a Python Shell window open. The application outputs both the unsorted and sorted lists.

Python Program to Sort List in Ascending Order, Sort Python List in Ascending Order : In this section, we discuss how to write a Python This python program allows a user to enter any integer value, and we consider it int(input("Please enter the Total Number of List Elements: ")) for i in range(1, Nested For Loop – Third Iteration: for 3 in range(1, 4) – Condition is True. Python get a list of strings as an input from a user. We can also accept a list of string as an input from the user using the same way as we did for a list of integers. Let’s see the demo. Python Program to get a list of string as input from a user. In this demo, we are accepting all family member names from a user.

Python sort List Function, Python sort List is used to sort a given list in ascending order. In this article, we will show you, How to use this Python List sort function with example. Let me change this key value to 3 nested list values. Python Sort List Example numList = [] number = int(input("Please enter the Number of List Elements: ")) for i in range​(1,  In this video we will see how we can perform list manipulation by taking input from a user in python Install our Android App from Google Play Store to get free access to videos, notes and codes

How to create a list based upon a user's inputs in Python 3.x, Python accepts inputs from users using the input() function. Like this: [code]x = input('enter a number: ') enter a number: 3 x Out[2]: '3' [/code]You notice that the 

Comments
  • this is the one that I understand the most at my level so thank you! How can I get the strings to be in order while it's still asking for user input though?
  • just put the "l.sort()" after "l.append(s.title())"
  • Hey guys. So I edit a bit and Create an application that accepts an unlimited number of names and then uses a sort to display them in alphabetical order. Example Output: Enter a name (-1 to quit): Brennan Enter a name (-1 to quit): Edgar Enter a name (-1 to quit): Allan Enter a name (-1 to quit): -1 Names are [Allan, Brennan, Edgar]