Python | Get a list as input from user - GeeksforGeeks
文章推薦指數: 80 %
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 ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesTakingmultipleinputsfromuserinPythonHowtoinputmultiplevaluesfromuserinonelineinPython?Python|GetalistasinputfromuserTakinginputinPythonTakinginputfromconsoleinPythonTop4AdvancedProjectIdeastoEnhanceYourAISkillsTop10MachineLearningProjectIdeasThatYouCanImplement5MachineLearningProjectIdeasforBeginnersin20227CoolPythonProjectIdeasforIntermediateDevelopers10InterestingPythonCoolTricks10EssentialPythonTipsAndTricksForProgrammersAmazinghacksofPythonPythonInputMethodsforCompetitiveProgrammingVulnerabilityininput()function–Python2.xPython|Outputusingprint()functionImportantdifferencesbetweenPython2.xandPython3.xwithexamplesPythonKeywordsKeywordsinPython|Set2NamespacesandScopeinPythonStatement,IndentationandCommentinPythonHowtoassignvaluestovariablesinPythonandotherlanguagesHowtoprintwithoutnewlineinPython?Pythonendparameterinprint()Python|sepparameterinprint()Python|OutputFormattingAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonHowtogetcolumnnamesinPandasdataframeTakingmultipleinputsfromuserinPythonHowtoinputmultiplevaluesfromuserinonelineinPython?Python|GetalistasinputfromuserTakinginputinPythonTakinginputfromconsoleinPythonTop4AdvancedProjectIdeastoEnhanceYourAISkillsTop10MachineLearningProjectIdeasThatYouCanImplement5MachineLearningProjectIdeasforBeginnersin20227CoolPythonProjectIdeasforIntermediateDevelopers10InterestingPythonCoolTricks10EssentialPythonTipsAndTricksForProgrammersAmazinghacksofPythonPythonInputMethodsforCompetitiveProgrammingVulnerabilityininput()function–Python2.xPython|Outputusingprint()functionImportantdifferencesbetweenPython2.xandPython3.xwithexamplesPythonKeywordsKeywordsinPython|Set2NamespacesandScopeinPythonStatement,IndentationandCommentinPythonHowtoassignvaluestovariablesinPythonandotherlanguagesHowtoprintwithoutnewlineinPython?Pythonendparameterinprint()Python|sepparameterinprint()Python|OutputFormattingAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonHowtogetcolumnnamesinPandasdataframePython|GetalistasinputfromuserViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 08Jul,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Weoftenencounterasituationwhenweneedtotakenumber/stringasinputfromtheuser.Inthisarticle,wewillseehowtogetasinputalistfromtheuser. Examples: Input:n=4,ele=1234 Output:[1,2,3,4] Input:n=6,ele=341796 Output:[3,4,1,7,9,6]Code#1:Basicexample Python3#creatinganemptylistlst=[] #numberofelementsasinputn=int(input("Enternumberofelements:")) #iteratingtilltherangeforiinrange(0,n): ele=int(input()) lst.append(ele)#addingtheelement print(lst)Output: Code#2:Withhandlingexception Python3#tryblocktohandletheexceptiontry: my_list=[] whileTrue: my_list.append(int(input())) #iftheinputisnot-integer,justprintthelistexcept: print(my_list)Output: Code#3:Usingmap() Python3#numberofelementsn=int(input("Enternumberofelements:")) #Belowlinereadinputsfromuserusingmap()function a=list(map(int,input("\nEnterthenumbers:").strip().split()))[:n] print("\nListis-",a)Output: Code#4:Listoflistsasinput Python3lst=[]n=int(input("Enternumberofelements:")) foriinrange(0,n): ele=[input(),int(input())] lst.append(ele) print(lst)Output: Code#5:UsingListComprehensionandTypecasting Python3#Forlistofintegerslst1=[] #Forlistofstrings/charslst2=[] lst1=[int(item)foritemininput("Enterthelistitems:").split()] lst2=[itemforitemininput("Enterthelistitems:").split()] print(lst1)print(lst2)Output: MyPersonalNotes arrow_drop_upSave LikePreviousHowtoinputmultiplevaluesfromuserinonelineinPython?Next TakinginputinPythonRecommendedArticlesPage:25,Feb1627,Mar1903,Jan2125,Jul2025,May2022,Sep2010,Dec2021,Jun2110,Feb1824,May1921,Nov1923,Apr2028,Apr2025,Jan2105,Jul2025,Jun2009,Jun2009,Jun2009,Jun2009,Jun2009,Jun2009,Jun2009,Jun2009,Jun20ArticleContributedBy:dileep1998@dileep1998VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:rahulsrivastava7sooda367ArticleTags:Pythonlist-programspython-listPythonPracticeTags:pythonpython-listReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Python | Get a list as input from user - GeeksforGeeks
In this article, we will see how to get as input a list from the user. Examples: Input : n = 4, e...
- 2How to take list input in Python in single line | Example code
To take list input in Python in a single line use input() function and split() function. Where in...
- 3[Day03]Python的基本運算!(上) - iT 邦幫忙
input()不管輸入什麼都是返回字串哦這點要注意! 匯入模組import. 使用import匯入需要的模組,通常我們會寫在程式的最上方。
- 4Python Accept List as a input From User - PYnative
- 5Get a list of numbers as input from the user - python
In Python 3.x, use this. a = [int(x) for x in input().split()]. Example. >>> a = [int(x) for x in...