What is the most efficient way to take user input in python list?

Viewed 614

My input will be something in the form of:

10
3 6 7 5 3 5 6 2 9 1
2 7 0 9 3 6 0 6 2 6

here 10 is the total number of elements. followed by two lines of input for two separate lists.

I am using the following lines to take the input:

n=int(input())
m=list(map(int,input().split()))[:n]
q=list(map(int,input().split()))[:n]

furthermore, I'll be sorting them using

m.sort()
q.sort()

It would be of great help if anyone could help me to find the most efficient method of doing the above steps. I did a few searches and landed onto various alternatives of taking the input but nowhere did I find as to what would be the most efficient way of solving this.

By efficiency, I mean in terms of time complexity. The above steps are fine when the numbers are small and the size of the list is small too. But I would have to feed a lot of much larger numbers and a much larger list thus affecting the efficiency of the code.

2 Answers

That's about as optimal as it gets.

If you're doing programming competitions, your bottleneck won't just be I/0, it will be your overall python runtime. It's inherently slower than C++/java, and some online judges fail to correctly account for this in the time limits.

    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.

    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, 4, 1, 7, 9, 6]

    Code #1: Basic example


<!-- language: lang-phyton -->

    # creating an empty list 
    lst = [] 

    # number of elemetns as input 
    n = int(input("Enter number of elements : ")) 

    # iterating till the range 
    for i in range(0, n): 
        ele = int(input()) 

        lst.append(ele) # adding the element 

    print(lst) 


    Code #2: With handling exception


<!-- language: lang-phyton -->
    # try block to handle the exception 
    try: 
        my_list = [] 

        while True: 
            my_list.append(int(input())) 

    # if input is not-integer, just print the list 
    except: 
        print(my_list) 



    Code #3: Using map()


<!-- language: lang-phyton -->
    # number of elements 
    n = int(input("Enter number of elements : ")) 

    # Below line read inputs from user using map() function  
    a = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n] 

    print("\nList is - ", a) 


    **Code #4: List of lists as input**


<!-- language: lang-phyton -->
    lst = [ ] 
    n = int(input("Enter number of elements : ")) 

    for i in range(0, n): 
        ele = [input(), int(input())] 
        lst.append(ele) 

    print(lst) 
Related