Constructing variables within a for loop The Next CEO of Stack OverflowHow to return multiple values from a function?Using global variables in a functionGetting the class name of an instance?Accessing the index in 'for' loops?How do I pass a variable by reference?Does Python have “private” variables in classes?Naming Classes - How to avoid calling everything a “<WhatEver>Manager”?Loop through an array in JavaScriptIterating over dictionaries using 'for' loopsWhy not inherit from List<T>?

I want to delete every two lines after 3rd lines in file contain very large number of lines :

Newlines in BSD sed vs gsed

Rotate a column

Do I need to write [sic] when a number is less than 10 but isn't written out?

What does "Its cash flow is deeply negative" mean?

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

Is French Guiana a (hard) EU border?

Why the difference in type-inference over the as-pattern in two similar function definitions?

Can a Bladesinger Wizard use Bladesong with a Hand Crossbow?

Can MTA send mail via a relay without being told so?

Are police here, aren't itthey?

0 rank tensor vs 1D vector

Tactics for judging if a printed image will be bright enough?

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Won the lottery - how do I keep the money?

Is a distribution that is normal, but highly skewed considered Gaussian?

Where do students learn to solve polynomial equations these days?

Why, when going from special to general relativity, do we just replace partial derivatives with covariant derivatives?

How to place nodes around a circle from some initial angle?

How many extra stops do monopods offer for tele photographs?

Why isn't the Mueller report being released completely and unredacted?

Is there a difference between "Fahrstuhl" and "Aufzug"

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?



Constructing variables within a for loop



The Next CEO of Stack OverflowHow to return multiple values from a function?Using global variables in a functionGetting the class name of an instance?Accessing the index in 'for' loops?How do I pass a variable by reference?Does Python have “private” variables in classes?Naming Classes - How to avoid calling everything a “<WhatEver>Manager”?Loop through an array in JavaScriptIterating over dictionaries using 'for' loopsWhy not inherit from List<T>?










0















Let's say I want to create a lot of instances of a class but don't want to write the variable name down for every instance.



What I want:



value1 = class(value1)
value2 = class(value2)
.
.
.


My idea was:



list = ['One','Two','Three']

for value in list:
value = class(value)


The result is not what I wanted. Python creates the variable 'value' and overrides it with the values of the list.



I'm sorry to ask such a basic question, but I'm not sure how to handle this.










share|improve this question



















  • 1





    Use a container like a list or a dict, in this case, a list seems appropriate

    – juanpa.arrivillaga
    Mar 21 at 18:09







  • 1





    values = [class(x) for x in list]

    – Blorgbeard
    Mar 21 at 18:13















0















Let's say I want to create a lot of instances of a class but don't want to write the variable name down for every instance.



What I want:



value1 = class(value1)
value2 = class(value2)
.
.
.


My idea was:



list = ['One','Two','Three']

for value in list:
value = class(value)


The result is not what I wanted. Python creates the variable 'value' and overrides it with the values of the list.



I'm sorry to ask such a basic question, but I'm not sure how to handle this.










share|improve this question



















  • 1





    Use a container like a list or a dict, in this case, a list seems appropriate

    – juanpa.arrivillaga
    Mar 21 at 18:09







  • 1





    values = [class(x) for x in list]

    – Blorgbeard
    Mar 21 at 18:13













0












0








0








Let's say I want to create a lot of instances of a class but don't want to write the variable name down for every instance.



What I want:



value1 = class(value1)
value2 = class(value2)
.
.
.


My idea was:



list = ['One','Two','Three']

for value in list:
value = class(value)


The result is not what I wanted. Python creates the variable 'value' and overrides it with the values of the list.



I'm sorry to ask such a basic question, but I'm not sure how to handle this.










share|improve this question
















Let's say I want to create a lot of instances of a class but don't want to write the variable name down for every instance.



What I want:



value1 = class(value1)
value2 = class(value2)
.
.
.


My idea was:



list = ['One','Two','Three']

for value in list:
value = class(value)


The result is not what I wanted. Python creates the variable 'value' and overrides it with the values of the list.



I'm sorry to ask such a basic question, but I'm not sure how to handle this.







python oop for-loop instance






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 21 at 18:24









petezurich

3,76581936




3,76581936










asked Mar 21 at 18:08









Blue SkyBlue Sky

31




31







  • 1





    Use a container like a list or a dict, in this case, a list seems appropriate

    – juanpa.arrivillaga
    Mar 21 at 18:09







  • 1





    values = [class(x) for x in list]

    – Blorgbeard
    Mar 21 at 18:13












  • 1





    Use a container like a list or a dict, in this case, a list seems appropriate

    – juanpa.arrivillaga
    Mar 21 at 18:09







  • 1





    values = [class(x) for x in list]

    – Blorgbeard
    Mar 21 at 18:13







1




1





Use a container like a list or a dict, in this case, a list seems appropriate

– juanpa.arrivillaga
Mar 21 at 18:09






Use a container like a list or a dict, in this case, a list seems appropriate

– juanpa.arrivillaga
Mar 21 at 18:09





1




1





values = [class(x) for x in list]

– Blorgbeard
Mar 21 at 18:13





values = [class(x) for x in list]

– Blorgbeard
Mar 21 at 18:13












2 Answers
2






active

oldest

votes


















1














First of all, note that you should not use list as a variable name, as it is reserved as a keyword by Python itself. Then, you could have another list, instanceList lets say, in which you will append every newly created instance of a class:



myList = ['One','Two','Three']
instanceList = []

for value in myList:
instanceList.append(class(value))





share|improve this answer






























    1














    You can use a list comprehension to build a list of class instances from a list of values:



    class A:
    def __init__(self, value):
    self.value = value

    values = ['One','Two','Three']
    instances = [A(v) for v in values]


    >>> print(list(o.value for o in instances))
    ['One', 'Two', 'Three']





    share|improve this answer























    • That is a generator expression, not a list comprehension...

      – juanpa.arrivillaga
      Mar 21 at 18:18











    • [A(v) for v in values] is a list comprehension - he just uses a generator expression to print the results.

      – Blorgbeard
      Mar 21 at 18:19











    • I'm not sure to understand your question/remark, but if you need a generator instead of a list, then you can just replace instances = [...] by instances = (...). Another legitimate option is to use a for-loop as mentioned in this answer.

      – cglacet
      Mar 21 at 18:21












    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55286706%2fconstructing-variables-within-a-for-loop%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    First of all, note that you should not use list as a variable name, as it is reserved as a keyword by Python itself. Then, you could have another list, instanceList lets say, in which you will append every newly created instance of a class:



    myList = ['One','Two','Three']
    instanceList = []

    for value in myList:
    instanceList.append(class(value))





    share|improve this answer



























      1














      First of all, note that you should not use list as a variable name, as it is reserved as a keyword by Python itself. Then, you could have another list, instanceList lets say, in which you will append every newly created instance of a class:



      myList = ['One','Two','Three']
      instanceList = []

      for value in myList:
      instanceList.append(class(value))





      share|improve this answer

























        1












        1








        1







        First of all, note that you should not use list as a variable name, as it is reserved as a keyword by Python itself. Then, you could have another list, instanceList lets say, in which you will append every newly created instance of a class:



        myList = ['One','Two','Three']
        instanceList = []

        for value in myList:
        instanceList.append(class(value))





        share|improve this answer













        First of all, note that you should not use list as a variable name, as it is reserved as a keyword by Python itself. Then, you could have another list, instanceList lets say, in which you will append every newly created instance of a class:



        myList = ['One','Two','Three']
        instanceList = []

        for value in myList:
        instanceList.append(class(value))






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 21 at 18:17









        Vasilis G.Vasilis G.

        3,9942924




        3,9942924























            1














            You can use a list comprehension to build a list of class instances from a list of values:



            class A:
            def __init__(self, value):
            self.value = value

            values = ['One','Two','Three']
            instances = [A(v) for v in values]


            >>> print(list(o.value for o in instances))
            ['One', 'Two', 'Three']





            share|improve this answer























            • That is a generator expression, not a list comprehension...

              – juanpa.arrivillaga
              Mar 21 at 18:18











            • [A(v) for v in values] is a list comprehension - he just uses a generator expression to print the results.

              – Blorgbeard
              Mar 21 at 18:19











            • I'm not sure to understand your question/remark, but if you need a generator instead of a list, then you can just replace instances = [...] by instances = (...). Another legitimate option is to use a for-loop as mentioned in this answer.

              – cglacet
              Mar 21 at 18:21
















            1














            You can use a list comprehension to build a list of class instances from a list of values:



            class A:
            def __init__(self, value):
            self.value = value

            values = ['One','Two','Three']
            instances = [A(v) for v in values]


            >>> print(list(o.value for o in instances))
            ['One', 'Two', 'Three']





            share|improve this answer























            • That is a generator expression, not a list comprehension...

              – juanpa.arrivillaga
              Mar 21 at 18:18











            • [A(v) for v in values] is a list comprehension - he just uses a generator expression to print the results.

              – Blorgbeard
              Mar 21 at 18:19











            • I'm not sure to understand your question/remark, but if you need a generator instead of a list, then you can just replace instances = [...] by instances = (...). Another legitimate option is to use a for-loop as mentioned in this answer.

              – cglacet
              Mar 21 at 18:21














            1












            1








            1







            You can use a list comprehension to build a list of class instances from a list of values:



            class A:
            def __init__(self, value):
            self.value = value

            values = ['One','Two','Three']
            instances = [A(v) for v in values]


            >>> print(list(o.value for o in instances))
            ['One', 'Two', 'Three']





            share|improve this answer













            You can use a list comprehension to build a list of class instances from a list of values:



            class A:
            def __init__(self, value):
            self.value = value

            values = ['One','Two','Three']
            instances = [A(v) for v in values]


            >>> print(list(o.value for o in instances))
            ['One', 'Two', 'Three']






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 21 at 18:17









            cglacetcglacet

            1,240819




            1,240819












            • That is a generator expression, not a list comprehension...

              – juanpa.arrivillaga
              Mar 21 at 18:18











            • [A(v) for v in values] is a list comprehension - he just uses a generator expression to print the results.

              – Blorgbeard
              Mar 21 at 18:19











            • I'm not sure to understand your question/remark, but if you need a generator instead of a list, then you can just replace instances = [...] by instances = (...). Another legitimate option is to use a for-loop as mentioned in this answer.

              – cglacet
              Mar 21 at 18:21


















            • That is a generator expression, not a list comprehension...

              – juanpa.arrivillaga
              Mar 21 at 18:18











            • [A(v) for v in values] is a list comprehension - he just uses a generator expression to print the results.

              – Blorgbeard
              Mar 21 at 18:19











            • I'm not sure to understand your question/remark, but if you need a generator instead of a list, then you can just replace instances = [...] by instances = (...). Another legitimate option is to use a for-loop as mentioned in this answer.

              – cglacet
              Mar 21 at 18:21

















            That is a generator expression, not a list comprehension...

            – juanpa.arrivillaga
            Mar 21 at 18:18





            That is a generator expression, not a list comprehension...

            – juanpa.arrivillaga
            Mar 21 at 18:18













            [A(v) for v in values] is a list comprehension - he just uses a generator expression to print the results.

            – Blorgbeard
            Mar 21 at 18:19





            [A(v) for v in values] is a list comprehension - he just uses a generator expression to print the results.

            – Blorgbeard
            Mar 21 at 18:19













            I'm not sure to understand your question/remark, but if you need a generator instead of a list, then you can just replace instances = [...] by instances = (...). Another legitimate option is to use a for-loop as mentioned in this answer.

            – cglacet
            Mar 21 at 18:21






            I'm not sure to understand your question/remark, but if you need a generator instead of a list, then you can just replace instances = [...] by instances = (...). Another legitimate option is to use a for-loop as mentioned in this answer.

            – cglacet
            Mar 21 at 18:21


















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55286706%2fconstructing-variables-within-a-for-loop%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해