Skip to content
    geeksforgeeks
    • Interview Prep
      • DSA
      • Interview Corner
      • Aptitude & Reasoning
      • Practice Coding Problems
      • All Courses
    • Tutorials
      • Python
      • Java
      • ML & Data Science
      • Programming Languages
      • Web Development
      • CS Subjects
      • DevOps
      • Software and Tools
      • School Learning
    • Tracks
      • Languages
        • Python
        • C
        • C++
        • Java
        • Advanced Java
        • SQL
        • JavaScript
        • C#
      • Interview Preparation
        • GfG 160
        • GfG 360
        • System Design
        • Core Subjects
        • Interview Questions
        • Interview Puzzles
        • Aptitude and Reasoning
        • Product Management
        • Computer Organisation and Architecture
      • Data Science
        • Python
        • Data Analytics
        • Complete Data Science
        • Gen AI
        • Agentic AI
      • Dev Skills
        • Full-Stack Web Dev
        • DevOps
        • Software Testing
        • CyberSecurity
        • NextJS
        • Git
      • Tools
        • Computer Fundamentals
        • AI Tools
        • MS Excel & Google Sheets
        • MS Word & Google Docs
      • Maths
        • Maths For Computer Science
        • Engineering Mathematics
        • School Maths
    • DSA
    • Practice Problems
    • C
    • C++
    • Java
    • Python
    • JavaScript
    • Data Science
    • Machine Learning
    • Courses
    • Linux
    • DevOps
    • SQL
    • Web Development
    • System Design
    • Aptitude
    Open In App

    Python Input Methods for Competitive Programming

    Last Updated : 17 Sep, 2025
    Comments
    Improve
    Suggest changes
    109 Likes
    Like
    Report

    Python is generally slower than C++ or Java, but choosing the right input method helps reduce time and avoid errors. Below, we’ll look at the most common input techniques in Python, when to use them, and their pros and cons.

    Example Problem 

    Let’s consider a problem: Find the sum of N numbers entered by the user.

    Example

    Input: 5
    1 2 3 4 5
    Output: 15

    We’ll now explore different input methods in Python that can help solve such problems efficiently.

    Different Input Methods

    Below are the main ways to take input in Python, Let’s go through them one by one.

    1. Normal Method

    This is the simplest and most commonly used method using input() for taking input and print() for displaying output.

    • input() always reads input as a string, so we need to typecast it (e.g., to int).
    • For arrays/lists, we can use split() and map() to convert them into integers.
    • It works fine for small inputs, but it is slow for large inputs, which is why competitive programmers prefer other methods.

    Example: This code takes n as the number of inputs, then reads n integers, sums them up and prints the result.

    Python
    n = int(input())
    arr = [int(x) for x in input().split()]
    summation = 0
    for x in arr:
        summation += x
    print(summation)
    

    Explanation:

    • first line n = int(input()) takes the number of elements.
    • second line reads the elements as space-separated integers.
    • loop calculates the sum and finally, print() displays the result.

    2. Faster Method Using stdin and stdout

    Python’s sys.stdin and sys.stdout are much faster than input() and print().

    • stdin.readline() reads input directly from the input buffer.
    • stdout.write() outputs results faster because it avoids the formatting overhead of print().

    This method is widely used in competitive programming for speed optimization.

    Example: This program reads input using stdin.readline(), computes the sum of numbers and prints it using stdout.write().

    Python
    from sys import stdin, stdout 
    def main():
        n = int(stdin.readline())
        arr = [int(x) for x in stdin.readline().split()]
        summation = sum(arr)
        stdout.write(str(summation))
    
    if __name__ == "__main__":
        main()
    

    Explanation:

    • stdin.readline() reads input as raw text much faster.
    • stdout.write() avoids extra formatting overhead of print().

    Timing comparison (100k lines each):

    • print(): 6.040s
    • Writing to file: 0.122s
    • stdout.write(): 0.121s

    Clearly, stdin + stdout is much faster.

    3. Taking User Input in Separate Variables

    Sometimes, we need to unpack multiple values directly into separate variables. For example, if input is:

    See More

    5 7 19 20

    We want:

    a = 5
    b = 7
    c = 19
    d = 20

    Instead of writing parsing code repeatedly, we can create a helper function.

    Example: This function reads a line of space-separated integers and unpacks them into variables.

    Python
    import sys
    def get_ints(): 
        return map(int, sys.stdin.readline().strip().split())
    a, b, c, d = get_ints()
    

    Explanation: get_ints() uses map(int, split()) to convert input into integers. The values are directly assigned to variables in one line.

    4. Taking User Inputs as a List of Integers

    When you want the entire line of numbers stored in a list, you can use another helper function. For example, input:

    1 2 3 4 5 6 7 8

    We want:

    Arr = [1, 2, 3, 4, 5, 6, 7, 8]

    Example: This program reads integers from a single line and stores them in a list.

    Python
    import sys
    def get_list(): 
        return list(map(int, sys.stdin.readline().strip().split()))
    Arr = get_list()
    

    Explanation: map(int, split()) converts all numbers to integers. Wrapping it in list() gives us a proper list. Now Arr holds all the integers as a list.

    5. Taking String Input Efficiently

    Sometimes, instead of numbers, we just need a string input. For example:

    GeeksforGeeks is the best platform to practice Coding.

    We want:

    string = "GeeksforGeeks if the best platform to practice coding."

    Example: This function reads a line of text input as a string.

    Python
    import sys
    def get_string(): 
        return sys.stdin.readline().strip()
    string = get_string()
    

    Explanation: sys.stdin.readline() reads the entire line. .strip() removes trailing newlines. The result is stored as a plain string.

    6. Adding a buffered pipe io (Python 2.7) 

    When inputs/outputs are very large, even sys.stdin may not be enough. In such cases, we can use a buffered pipe (io.BytesIO) to further speed up I/O. This is more advanced and usually required only for problems with huge input sizes (2MB+ files).

    Example: This program uses a buffer to speed up output operations.

    Python
    import atexit, io, sys
    
    # A buffer for output
    buffer = io.BytesIO()
    sys.stdout = buffer
    
    # Print via buffer
    @atexit.register
    def write():
        sys.__stdout__.write(buffer.getvalue())
    
    #####################################
    # Example program
    n = int(input())
    arr = [int(x) for x in input().split()]
    summation = sum(arr)
    print(summation)
    

    Explanation: Output is written into an in-memory buffer instead of directly printing. At program exit, atexit.register writes all data at once. This reduces the overhead of multiple print() calls.

    Create Quiz

    K

    kartik
    Improve

    K

    kartik
    Improve
    Article Tags :
    • Competitive Programming

    Explore

      Basics

      DSA Tutorial - Learn Data Structures and Algorithms

      6 min read

      Maths for DSA

      15+ min read

      Mathematical Algorithms

      5 min read

      Bit manipulation

      Bit Manipulation for Competitive Programming

      15+ min read

      Bit Tricks for Competitive Programming

      7 min read

      Bitwise Hacks for Competitive Programming

      14 min read

      DP for CP

      Dynamic Programming (DP) Introduction

      15+ min read

      Dynamic Programming or DP

      3 min read

      DP on Trees for Competitive Programming

      15+ min read

      Dynamic Programming in Game Theory for Competitive Programming

      15+ min read

      Advanced

      Graph Algorithms

      3 min read

      Segment Tree

      2 min read

      Binary Indexed Tree or Fenwick Tree

      15 min read

      Array Range Queries

      3 min read
    top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Campus Training Program
  • Explore
  • POTD
  • Job-A-Thon
  • Blogs
  • Nation Skill Up
  • Tutorials
  • Programming Languages
  • DSA
  • Web Technology
  • AI, ML & Data Science
  • DevOps
  • CS Core Subjects
  • Interview Preparation
  • Software and Tools
  • Courses
  • ML and Data Science
  • DSA and Placements
  • Web Development
  • Programming Languages
  • DevOps & Cloud
  • GATE
  • Trending Technologies
  • Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
  • Preparation Corner
  • Interview Corner
  • Aptitude
  • Puzzles
  • GfG 160
  • System Design
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences