How To Input A List In Python - Edureka
文章推薦指數: 80 %
This article will introduce you to different ways to input a list in Python and give you a detailed programmatic demonstration. HomeBlogDataScienceHowToInputAListInPython?PythonProgramming(134Blogs)BecomeaCertifiedProfessionalAWSGlobalInfrastructureIntroductiontoPythonLearnPythonProgramming–OneStopSolutionforBeginnersWhatisPython?Isiteasytolearn?PythonTutorial–PythonProgrammingForBeginnersPython:InterestingFactsYouNeedToKnowWhicharethebestbooksforPython?Top10FeaturesofPythonYouNeedtoKnowTop10PythonApplicationsintheRealWorldYouNeedtoKnowPythonAnacondaTutorial:EverythingYouNeedToKnowTop10ReasonsWhyYouShouldLearnPythonWhatareImportantAdvantagesandDisadvantagesOfPython?PythonandNetflix:WhatHappensWhenYouStreamaFilm?HowtoLearnPython3fromScratch–ABeginnersGuideTop10BestIDEforPython:HowtochoosethebestPythonIDE?HowToUsePythonForDevOps?PythonvsC:KnowwhatarethedifferencesPythonvsC++:KnowwhatarethedifferencesRubyvsPython:WhataretheDifferences?PythonInstallationInstallPythonOnWindows–Python3.XInstallationGuideHowToRunPythonInUbuntu(Linux)?WhatisPythonSpyderIDEandHowtouseit?HowToAddPythontoPath?IntroductiontoAtomPythonTextEditorandhowtoconfigureitPython101:HelloWorldProgramPythonFundamentalsPythonBasics:WhatmakesPythonsoPowerful?DataStructuresYouNeedToLearnInPythonWhatistheuseofselfinPython?PythonProgramming–BeginnersGuideToPythonProgrammingLanguageWhatisprintinPythonandHowtouseitsParameters?ImportantPythonDataTypesYouNeedtoKnowPyCharmTutorial:WritingPythonCodeInPyCharm(IDE)PythonVisualStudio-LearnHowToMakeYourFirstPythonProgramWhatistheMainFunctioninPythonandhowtouseit?WhatisTryExceptinPythonandhowitworks?WhatareCommentsinPythonandhowtousethem?HowtofetchandmodifyDateandTimeinPython?InheritanceInPythonWithExamples:AllYouNeedToKnowHowToBestUtilizePythonCGIInDayToDayCoding?PythonConstructors:EverythingYouNeedToKnowHowToCreateYourFirstPythonMetaclass?InitInPython:EverythingYouNeedToKnowLearnHowToUseSplitFunctionInPythonHowtoReadCSVFileinPython?StackinPython:How,whyandwhere?HashTablesandHashmapsinPython:WhataretheyandHowtoimplement?WhatisRandomNumberGeneratorinPythonandhowtouseit?HowtofindSquareRootinPython?ArraysinPython–WhatarePythonArraysandhowtousethem?LoopsInPython:WhyShouldYouUseOne?WhatareSetsinPythonandHowtousethem?WhatisMethodOverloadinginPythonandHowitWorks?PythonFunctions:ACompleteBeginnersGuideLearnHowToUseMapFunctionInPythonWithExamplesPythontimesleep()–OneStopSolutionfortime.sleep()MethodHowToReverseAStringInPython?HowToSortADictionaryInPython:SortByKeys,SortByValuesStringFunctionInPython:HowToUseItwithExamplesHowToConvertDecimalToBinaryInPythonTupleInPython:EverythingYouNeedToKnowHowToInputaListinPython?HowtoFindLengthofListinPython?HowtoReverseaListinPython:LearnPythonListReverse()MethodLearnWhatisRangeinPythonWithExamplesEverythingYouNeedToKnowAboutHashInPythonWhatIsinstanceInPythonAndHowToImplementIt?HowToBestImplementArmstrongNumberInPython?HowToImplementRoundFunctionInPython?HowToImplement2-DarraysinPython?LearnHowToMakePythonPatternProgramsWithExamplesIntroductionToFileHandlingInPythonWhatisPythonJSONandHowtoimplementit?ThreadingInPython:LearnHowToWorkWithThreadsInPythonHowToBestImplementMultiprocessingInPython?KnowallAboutRobotFrameworkWithPythonWhatisMutithreadinginPythonandHowtoAchieveit?Map,FilterandReduceFunctionsinPython:AllyouneedtoknowWhatistheFormatFunctioninPythonandHowdoesitwork?PythonDatabaseConnection:KnowhowtoconnectwithdatabaseWhatareLambdaFunctionsandHowtoUseThem?WhatareGeneratorsinPythonandHowtousethem?PythonIterators:WhatisIteratorinPythonandhowtouseit?PythonForLoopTutorialWithExamplesToPracticeWhileLoopInPython:AllYouNeedToKnowWhatisSocketProgramminginPythonandhowtomasterit?CheatSheetToPythonRegExWithExamplesHowtoParseandModifyXMLinPython?PythonOOPsObjectOrientedProgrammingPython:AllyouneedtoknowPythonClass–ObjectOrientedProgrammingWhatisPolymorphisminOOPsprogramming?PythonStringConcatenation:EverythingYouNeedToKnowEverythingYouNeedToKnowAboutPrintExceptionInPythonPythonLibrariesTop10PythonLibrariesYouMustKnowIn2022HowToInstallNumPyInPython?PythonNumPyTutorial–IntroductionToNumPyWithExamplesPythonPandasTutorial:LearnPandasforDataAnalysisPythonMatplotlibTutorial–DataVisualizationsInPythonWithMatplotlibPythonSeabornTutorial:WhatisSeabornandHowtoUseit?SciPyTutorial:WhatisPythonSciPyandHowtouseit?HowToMakeAChatbotInPython?FIFAWorldCup2018BestXI:AnalyzingFifaDatasetUsingPythonScikitlearn–MachineLearningusingPythonTheWhyAndHowOfExploratoryDataAnalysisInPythonOpenCVPythonTutorial:ComputerVisionWithOpenCVInPythonTkinterTutorialForBeginners|GUIProgrammingUsingTkinterInPythonIntroductionToGameBuildingWithPython'sTurtleModulePyGameTutorial–GameDevelopmentUsingPyGameInPythonPyTorchTutorial–ImplementingDeepNeuralNetworksUsingPyTorchScrapyTutorial:HowToMakeAWeb-CrawlerUsingScrapy?WebScrapingABeginner'sGuidetolearnwebscrapingwithpython!PythonRequestsModuleTutorial–SendingHTTPRequestsUsingRequestsModuleDjangoDjangoTutorial–WebDevelopmentwithPythonDjangoFrameworkDjangovsFlask:WhichisthebestforyourWebApplication?Top50DjangoInterviewQuestionsandAnswersYouNeedtoKnowin2022PythonProgramsHowtoCheckaNumberisPalindromeinPython?HowtoFindPrimeNumbersinPythonHowToImplementGCDInPython?HowToConvertListsToStringsInPython?HowtoDisplayFibonacciSeriesinPython?HowtoimplementPythonprogramtocheckLeapYear?HowtoreverseanumberinPython?HowtoImplementaLinkedListinPython?HowtoimplementBubbleSortinPython?HowtoimplementMergeSortinPython?A101GuideOnTheLeastSquaresRegressionMethodCareerOppurtunitiesPythonCareerOpportunities:YourCareerGuideToPythonProgrammingTopPythondeveloperSkillsyouneedtoknowLearnHowToMakeAResumeForAPythonDeveloperWhatistheAveragePythonDeveloperSalary?HowToBecomeAPythonDeveloper:LearningPathForPythonWhyYouShouldChoosePythonForBigDataInterviewQuestionsTop100+PythonInterviewQuestionsYouMustPrepareIn2022Top50ImportantOOPsInterviewQuestionsandAnswersin2022TopPythonProjectsYouShouldConsiderLearningDataScienceTopicsCoveredBusinessAnalyticswithR(32Blogs)DataScience(39Blogs)MasteringPython(71Blogs)DecisionTreeModelingUsingR(1Blogs)SEEMOREHowToInputaListinPython?LastupdatedonJul13,2022155.2KViewsShareWhatsAppLinkedinTwitterFacebookRedditCopyLink!edurekaBookmarkCopyLink!36/62BlogfromPythonFundamentalsBecomeaCertifiedProfessionalSometimeswhilecodinginPython,youwillneedtotakealistasaninput.Whilethismightsoundsimpleatfirst,itisoftenregardedasacomplextasktoaccomplishforabeginner.ThisarticlewilltellyouhowtoinputalistinPython.Followingpointerswillbecoveredinthisarticle,InputaListinPythonAcceptalistofnumberasaninputinPythonAcceptaListofStringsfromtheUserExamplesSoletusgetstartedthen,InputaListinPythonAsyoumightalreadyknow,inordertoacceptaninputfromtheuserinPython,wecanmakeuseoftheinput()function.Whenused,itenablestheprogrammertoaccepteitherastring,integerorevenacharacterasaninputfromtheuser.Butwhenitcomestoacceptingalistasaninput,theapproachwefollowisslightlydifferent.ThishowtoinputaListinPythonarticle,willaddressmainareasofconcernFindoutourPythonTraininginTopCities/CountriesIndiaUSAOtherCities/CountriesBangaloreNewYorkUKHyderabadChicagoLondonDelhiAtlantaCanadaChennaiHoustonTorontoMumbaiLosAngelesAustraliaPuneBostonUAEKolkataMiamiDubaiAhmedabadSanFranciscoPhilippinesAcceptalistofnumberasaninputinPythonTakealookattheexampleprogrambelow,whichacceptsalistofnumbersasaninputinPython.input_string=input("Enteralistelementseparatedbyspace") list =input_string.split() print("Calculatingsumofelementofinputlist") sum=0 fornuminlist: sum+=int(num) print("Sum=",sum)Whentheaboveprogramisrun,theoutputwilllooksomethinglikethis.OutputEnteralistelementseparatedbyspace2469CalculatingsumofelementofinputlistSum= 20AnalysisNowletusbreakdowntheprogramandseehowtheworkingsbehindit.Asyoualreadyknow,wheneverweusetheinput()functioninPython,itconvertstheuserinputintoastring.Thereforeintheaboveprogram,weacceptedalistelementfromauserintheformofastringwhichisseparatedbyspaces.Onethingtonotehere,isthatyouhavetheabilitytoacceptastringseparatedbytheoperatorcomma(,)aswell.Butinthissituationyouneedtomakeuseofthesplit()functioninordertopasstheargumentaswellastheseparatorinthePythonprogram.Ifyoulookclosely,youwillfindthatwehavemadeuseofthefunctioninput_string.split()tosplittheinputstringseparatedbyspacesfromtheuserandconvertedthemintoindividualelementstobeaddedintoalist.WehavealsomadeuseoftheForloopandconvertedeveryelementintoanintegertocalculateitssum.Movingontothenexttopicofthisarticleletussee howtoinputalistinpythonthatholdsstrings,AcceptaListofStringsfromtheUserSimilartotheaboveprogram,wehavetheabilitytocreateaprograminPythontoacceptalistofstringsfromtheuser.Takealookattheexamplebelowtounderstandthisbetter.input_string=input("Enterfamilymembersseparatedbycomma") family_list =input_string.split(",") print("Printingallfamilymembernames") fornameinfamily_list: print(name)Whentheaboveprogramisrun,theoutputwilllooksomethinglikethis.Enterfamilymembersseparatedbycomma:Julius,Mark,JohnPrintingallfamilymembernamesJuluisMarkJohnAnalysisLetusbreakdowntheaboveprogramintopointersandunderstanditbetter.Similartotheearlierexample,weacceptedaninputlistfromtheuserintheformofastringseparatedbycommas.Wehavemadeuseoftheinput_string.split(“,”)functiontosplitthestringseparatedbycommasandconvertitintoalistofstringtobeusedintheprogram.Weusedaforloopandprintedoutallfamilynamesinorder,asyoucanseeintheoutputsharedabove.Movingonletusseehowthisconceptfaresfromprogrammingperspective,ExamplesLetustakealookatacoupleofotherexamplestounderstandhowtoinputalistinPython.Example1#creatinganemptylist lst=[] #numberofelemetnsasinput n=int(input("Enternumberofelements:")) #iteratingtilltherange foriinrange(0,n): ele=int(input()) lst.append(ele)#addingtheelement print(lst)OutputLetustakealookatthenextexample,Example2#tryblocktohandletheexception try: my_list=[] whileTrue: my_list.append(int(input())) #ifinputisnot-integer,justprintthelist except: print(my_list)OutputExample3#numberofelements n=int(input("Enternumberofelements:")) #Belowlinereadinputsfromuserusingmap()function a=list(map(int,input("nEnterthenumbers:").strip().split()))[:n] print("nListis-",a)Thiswouldbethefinalexampleofthisarticle,Example4lst=[] n=int(input("Enternumberofelements:")) foriinrange(0,n): ele=[input(),int(input())] lst.append(ele) print(lst)OutputThisisitguysthisbringsustotheendofthisarticleon HowToInputAListInPython?Togetin-depthknowledgeonPythonalongwithitsvariousapplications,youcan enrollnowforliveonlinePythontrainingwith24/7supportandlifetimeaccess.Gotaquestionforus?Mentiontheminthecommentssectionof articleandwewillgetbacktoyouorjoinourPythonMastercourse.UpcomingBatchesForPythonCertificationTrainingCourseCourseNameDatePythonCertificationTrainingCourseClassStartson27thAugust,202227thAugustSAT&SUN(WeekendBatch)ViewDetailsPythonCertificationTrainingCourseClassStartson24thSeptember,202224thSeptemberSAT&SUN(WeekendBatch)ViewDetailsRecommendedvideosforyouPythonProgramming–LearnPythonProgrammingFromScratchWatchNowMasteringPython:AnExcellenttoolforWebScrapingandDataAnalysisWatchNowLinearRegressionWithRWatchNowKnowTheScienceBehindProductRecommendationWithRProgrammingWatchNowIntroductiontoBusinessAnalyticswithRWatchNowDiversityOfPythonProgrammingWatchNowBusinessAnalyticsDecisionTreeinRWatchNowPythonList,Tuple,String,SetAndDictonary–PythonSequencesWatchNowTheWhysandHowsofPredictiveModeling-IIWatchNowPythonTutorial–AllYouNeedToKnowInPythonProgrammingWatchNowApplicationofClusteringinDataScienceUsingReal-TimeExamplesWatchNowPythonNumpyTutorial–ArraysInPythonWatchNowPythonLoops–While,ForandNestedLoopsinPythonProgrammingWatchNowBusinessAnalyticswithRWatchNowMachineLearningwithPythonWatchNowAndroidDevelopment:UsingAndroid5.0LollipopWatchNowPythonforBigDataAnalyticsWatchNowSentimentAnalysisInRetailDomainWatchNowWebScrapingAndAnalyticsWithPythonWatchNowDataScience:MakeSmarterBusinessDecisionsWatchNowRecommendedblogsforyouHowToBecomeAMachineLearningEngineer?–LearningPathReadArticleABeginner’sguideto“WhatisRProgramming?”ReadArticleWhatisUnsupervisedLearningandHowdoesitWork?ReadArticleTop10DataScienceCertificationsin2022–YourPathtoBecomeaDataScientist!ReadArticleTop10ReasonsWhyYouShouldLearnPythonReadArticleLearnHowToMakeSimpleMobileApplicationsUsingThisKivyTutorialInPythonReadArticlePyGameTutorial–GameDevelopmentUsingPyGameInPythonReadArticleWhyShouldaStatisticalProfessionalKnowR?ReadArticleLinearRegressionAlgorithmfromScratchReadArticleEverythingYouNeedToKnowAboutMatrixInPythonReadArticlePythonConstructors:EverythingYouNeedToKnowReadArticleFIFAWorldCup2018BestXI:AnalyzingFifaDatasetUsingPythonReadArticleHowToImplement2-DarraysinPython?ReadArticlePython:InterestingFactsYouNeedToKnowReadArticleHowToCreateYourFirstPythonMetaclass?ReadArticleWorldCup2018:5GameChangingTechnologiesinFootballReadArticleAComprehensiveGuideToRandomForestInRReadArticleRShinyTutorial:AllyouNeedtoKnowReadArticleWhatisBusinessAnalytics?AllyouNeedtoKnowReadArticlePythonvsC++:KnowwhatarethedifferencesReadArticleComments0CommentsJointhediscussion CancelreplyTrendingCoursesinDataScienceDataScienceandMachineLearningInternship...1kEnrolledLearnersWeekend/WeekdayLiveClassReviews5(50)DataSciencewithPythonCertificationCourse107kEnrolledLearnersWeekend/WeekdayLiveClassReviews5(42800)PythonCertificationTrainingCourse37kEnrolledLearnersWeekendLiveClassReviews5(14550)PythonMachineLearningCertificationTrainin...13kEnrolledLearnersWeekendLiveClassReviews5(4900)DataSciencewithRProgrammingCertification...39kEnrolledLearnersWeekendLiveClassReviews5(15550)DataAnalyticswithRProgrammingCertificati...26kEnrolledLearnersWeekendLiveClassReviews5(10150)SASTrainingandCertification6kEnrolledLearnersWeekend/WeekdaySelfPacedReviews5(2100)StatisticsEssentialsforAnalytics7kEnrolledLearnersWeekend/WeekdaySelfPacedReviews5(2500)AnalyticsforRetailBanks2kEnrolledLearnersWeekend/WeekdaySelfPacedReviews5(600)AdvancedPredictiveModellinginRCertificat...4kEnrolledLearnersWeekendSelfPacedReviews4(1600)BrowseCategoriesArtificialIntelligenceBIandVisualizationBigDataBlockchainCloudComputingCyberSecurityDataWarehousingandETLDatabasesDevOpsDigitalMarketingEnterpriseFrontEndWebDevelopmentMobileDevelopmentOperatingSystemsProductManagementProgramming&FrameworksProjectManagementandMethodologiesRoboticProcessAutomationSoftwareTestingSystems&ArchitectureREGISTERFORFREEWEBINARSendOTPYearsofExperience*Student0-2Years2-5Years5-10Years10+YearsREGISTERNOWThankyouforregisteringJoinEdurekaMeetupcommunityfor100+FreeWebinarseachmonthJOINMEETUPGROUPSubscribetoourNewsletter,andgetpersonalizedrecommendations.SignupwithGoogleSignupwithFacebookAlreadyhaveanaccount?Signin.××20,00,000learnersloveus!Getpersonalisedresourcesinyourinbox.SignupwithGmailSignupwithFacebookORPleaseprovideavalidinputPasswordmusthaveAtleast1upper-caseand1lower-caseletterMinimum8charactersandMaximum50charactersSIGNUPAlreadyhaveanEdurekaAccount?LoginPleaseenteravalidemailidForgotPassword?LOGINDon’thaveedurekaaccount?SignUpresend?PasswordmusthaveAtleast1upper-caseand1lower-caseletterMinimum8charactersandMaximum50charactersresetpasswordDon’thaveedurekaaccount?SignUpresetpasswordDon’thaveedurekaaccount?SignUpSendCodeDon’thaveedurekaaccount?SignUp×ReshapeYourCareer!Name*EmailID*PhoneNumber*YourTotalWorkExperience*YearsofExperience*Student0-2Years2-5Years5-10Years10+YearsApplyNowAwesomeWehaverecievedyourcontactdetails.Youwillrecieveanemailfromusshortly.×MainheadingsubheadingClicktoavail"PMP®","PMI®","PMI-ACP®"and"PMBOK®"areregisteredmarksoftheProjectManagementInstitute,Inc.MongoDB®,MongoandtheleaflogoaretheregisteredtrademarksofMongoDB,Inc.HowToInputaListinPython?edureka.coWhatsappLinkedinTwitterFacebookRedditCopyLink
延伸文章資訊
- 1Python Accept List as a input From User - PYnative
- 2User Input For List | Python Programs - YouTube
- 3How 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...
- 4How To Input a List in Python - Besant Technologies
How to Input a list in python? ... The list is one of the data structure in python. It is basical...
- 5Python Get a list as input from user - Tutorialspoint
We can also use input function twice so that we can create a list of lists. Use the range functio...