What do [] brackets in a for loop in python mean?











up vote
4
down vote

favorite
1












I'm parsing JSON objects and found this sample line of code which I kind of understand but would appreciate a more detailed explanation of:



for record in [x for x in records.split("n") if x.strip() != '']:


I know it is spliting records to get individual records by the new line character however I was wondering why it looks so complicated? is it a case that we can't have something like this:



for record in records.split("n") if x.strip() != '']:


So what do the brackets do ? and why do we have x twice in x for x in records.split....



Thanks










share|improve this question






















  • It's a list comprehension, see related: stackoverflow.com/questions/16341775/…
    – EdChum
    Jun 5 '15 at 15:26










  • EdChum is right (duh); note that it doesn't have to do with loops in particular. This notation is a terse way to create lists. A loop can iterate also over lists.
    – Ami Tavory
    Jun 5 '15 at 15:28






  • 2




    Thanks for both of you inputs, on a side note people love down voting question on here. If you're going to vote a question down then I think you should leave a comment saying why. I think it's a valid programming question which I couldn't find anywhere else or know how to search for.
    – Mo.
    Jun 5 '15 at 15:38










  • @Mo. see: stackoverflow.com/questions/38229059/…
    – oba2311
    Mar 8 '17 at 13:24















up vote
4
down vote

favorite
1












I'm parsing JSON objects and found this sample line of code which I kind of understand but would appreciate a more detailed explanation of:



for record in [x for x in records.split("n") if x.strip() != '']:


I know it is spliting records to get individual records by the new line character however I was wondering why it looks so complicated? is it a case that we can't have something like this:



for record in records.split("n") if x.strip() != '']:


So what do the brackets do ? and why do we have x twice in x for x in records.split....



Thanks










share|improve this question






















  • It's a list comprehension, see related: stackoverflow.com/questions/16341775/…
    – EdChum
    Jun 5 '15 at 15:26










  • EdChum is right (duh); note that it doesn't have to do with loops in particular. This notation is a terse way to create lists. A loop can iterate also over lists.
    – Ami Tavory
    Jun 5 '15 at 15:28






  • 2




    Thanks for both of you inputs, on a side note people love down voting question on here. If you're going to vote a question down then I think you should leave a comment saying why. I think it's a valid programming question which I couldn't find anywhere else or know how to search for.
    – Mo.
    Jun 5 '15 at 15:38










  • @Mo. see: stackoverflow.com/questions/38229059/…
    – oba2311
    Mar 8 '17 at 13:24













up vote
4
down vote

favorite
1









up vote
4
down vote

favorite
1






1





I'm parsing JSON objects and found this sample line of code which I kind of understand but would appreciate a more detailed explanation of:



for record in [x for x in records.split("n") if x.strip() != '']:


I know it is spliting records to get individual records by the new line character however I was wondering why it looks so complicated? is it a case that we can't have something like this:



for record in records.split("n") if x.strip() != '']:


So what do the brackets do ? and why do we have x twice in x for x in records.split....



Thanks










share|improve this question













I'm parsing JSON objects and found this sample line of code which I kind of understand but would appreciate a more detailed explanation of:



for record in [x for x in records.split("n") if x.strip() != '']:


I know it is spliting records to get individual records by the new line character however I was wondering why it looks so complicated? is it a case that we can't have something like this:



for record in records.split("n") if x.strip() != '']:


So what do the brackets do ? and why do we have x twice in x for x in records.split....



Thanks







python






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 5 '15 at 15:25









Mo.

11.8k2766115




11.8k2766115












  • It's a list comprehension, see related: stackoverflow.com/questions/16341775/…
    – EdChum
    Jun 5 '15 at 15:26










  • EdChum is right (duh); note that it doesn't have to do with loops in particular. This notation is a terse way to create lists. A loop can iterate also over lists.
    – Ami Tavory
    Jun 5 '15 at 15:28






  • 2




    Thanks for both of you inputs, on a side note people love down voting question on here. If you're going to vote a question down then I think you should leave a comment saying why. I think it's a valid programming question which I couldn't find anywhere else or know how to search for.
    – Mo.
    Jun 5 '15 at 15:38










  • @Mo. see: stackoverflow.com/questions/38229059/…
    – oba2311
    Mar 8 '17 at 13:24


















  • It's a list comprehension, see related: stackoverflow.com/questions/16341775/…
    – EdChum
    Jun 5 '15 at 15:26










  • EdChum is right (duh); note that it doesn't have to do with loops in particular. This notation is a terse way to create lists. A loop can iterate also over lists.
    – Ami Tavory
    Jun 5 '15 at 15:28






  • 2




    Thanks for both of you inputs, on a side note people love down voting question on here. If you're going to vote a question down then I think you should leave a comment saying why. I think it's a valid programming question which I couldn't find anywhere else or know how to search for.
    – Mo.
    Jun 5 '15 at 15:38










  • @Mo. see: stackoverflow.com/questions/38229059/…
    – oba2311
    Mar 8 '17 at 13:24
















It's a list comprehension, see related: stackoverflow.com/questions/16341775/…
– EdChum
Jun 5 '15 at 15:26




It's a list comprehension, see related: stackoverflow.com/questions/16341775/…
– EdChum
Jun 5 '15 at 15:26












EdChum is right (duh); note that it doesn't have to do with loops in particular. This notation is a terse way to create lists. A loop can iterate also over lists.
– Ami Tavory
Jun 5 '15 at 15:28




EdChum is right (duh); note that it doesn't have to do with loops in particular. This notation is a terse way to create lists. A loop can iterate also over lists.
– Ami Tavory
Jun 5 '15 at 15:28




2




2




Thanks for both of you inputs, on a side note people love down voting question on here. If you're going to vote a question down then I think you should leave a comment saying why. I think it's a valid programming question which I couldn't find anywhere else or know how to search for.
– Mo.
Jun 5 '15 at 15:38




Thanks for both of you inputs, on a side note people love down voting question on here. If you're going to vote a question down then I think you should leave a comment saying why. I think it's a valid programming question which I couldn't find anywhere else or know how to search for.
– Mo.
Jun 5 '15 at 15:38












@Mo. see: stackoverflow.com/questions/38229059/…
– oba2311
Mar 8 '17 at 13:24




@Mo. see: stackoverflow.com/questions/38229059/…
– oba2311
Mar 8 '17 at 13:24












3 Answers
3






active

oldest

votes

















up vote
12
down vote



accepted










The "brackets" in your example constructs a new list from an old one, this is called list comprehension.



The basic idea with [f(x) for x in xs if condition] is:



def list_comprehension(xs):
result =
for x in xs:
if condition:
result.append(f(x))
return result


The f(x) can be any expression, containing x or not.






share|improve this answer






























    up vote
    1
    down vote













    That's a list comprehension, a neat way of creating lists with certain conditions on the fly.



    You can make it a short form of this:



    a = 
    for record in records.split("n"):
    if record.strip() != '':
    a.append(record)

    for record in a:
    # do something





    share|improve this answer




























      up vote
      0
      down vote













      The square brackets ( ) usually signal a list in Python.






      share|improve this answer





















      • Yes, they signal a list, but what else?
        – Zizouz212
        Jun 5 '15 at 15:52











      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',
      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%2f30670310%2fwhat-do-brackets-in-a-for-loop-in-python-mean%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      12
      down vote



      accepted










      The "brackets" in your example constructs a new list from an old one, this is called list comprehension.



      The basic idea with [f(x) for x in xs if condition] is:



      def list_comprehension(xs):
      result =
      for x in xs:
      if condition:
      result.append(f(x))
      return result


      The f(x) can be any expression, containing x or not.






      share|improve this answer



























        up vote
        12
        down vote



        accepted










        The "brackets" in your example constructs a new list from an old one, this is called list comprehension.



        The basic idea with [f(x) for x in xs if condition] is:



        def list_comprehension(xs):
        result =
        for x in xs:
        if condition:
        result.append(f(x))
        return result


        The f(x) can be any expression, containing x or not.






        share|improve this answer

























          up vote
          12
          down vote



          accepted







          up vote
          12
          down vote



          accepted






          The "brackets" in your example constructs a new list from an old one, this is called list comprehension.



          The basic idea with [f(x) for x in xs if condition] is:



          def list_comprehension(xs):
          result =
          for x in xs:
          if condition:
          result.append(f(x))
          return result


          The f(x) can be any expression, containing x or not.






          share|improve this answer














          The "brackets" in your example constructs a new list from an old one, this is called list comprehension.



          The basic idea with [f(x) for x in xs if condition] is:



          def list_comprehension(xs):
          result =
          for x in xs:
          if condition:
          result.append(f(x))
          return result


          The f(x) can be any expression, containing x or not.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Sep 2 at 1:39









          ʇolɐǝz ǝɥʇ qoq

          65811228




          65811228










          answered Jun 5 '15 at 15:29









          folkol

          3,5411222




          3,5411222
























              up vote
              1
              down vote













              That's a list comprehension, a neat way of creating lists with certain conditions on the fly.



              You can make it a short form of this:



              a = 
              for record in records.split("n"):
              if record.strip() != '':
              a.append(record)

              for record in a:
              # do something





              share|improve this answer

























                up vote
                1
                down vote













                That's a list comprehension, a neat way of creating lists with certain conditions on the fly.



                You can make it a short form of this:



                a = 
                for record in records.split("n"):
                if record.strip() != '':
                a.append(record)

                for record in a:
                # do something





                share|improve this answer























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  That's a list comprehension, a neat way of creating lists with certain conditions on the fly.



                  You can make it a short form of this:



                  a = 
                  for record in records.split("n"):
                  if record.strip() != '':
                  a.append(record)

                  for record in a:
                  # do something





                  share|improve this answer












                  That's a list comprehension, a neat way of creating lists with certain conditions on the fly.



                  You can make it a short form of this:



                  a = 
                  for record in records.split("n"):
                  if record.strip() != '':
                  a.append(record)

                  for record in a:
                  # do something






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 5 '15 at 15:28









                  Zizouz212

                  3,25142755




                  3,25142755






















                      up vote
                      0
                      down vote













                      The square brackets ( ) usually signal a list in Python.






                      share|improve this answer





















                      • Yes, they signal a list, but what else?
                        – Zizouz212
                        Jun 5 '15 at 15:52















                      up vote
                      0
                      down vote













                      The square brackets ( ) usually signal a list in Python.






                      share|improve this answer





















                      • Yes, they signal a list, but what else?
                        – Zizouz212
                        Jun 5 '15 at 15:52













                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      The square brackets ( ) usually signal a list in Python.






                      share|improve this answer












                      The square brackets ( ) usually signal a list in Python.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jun 5 '15 at 15:31









                      uniqueusername

                      10318




                      10318












                      • Yes, they signal a list, but what else?
                        – Zizouz212
                        Jun 5 '15 at 15:52


















                      • Yes, they signal a list, but what else?
                        – Zizouz212
                        Jun 5 '15 at 15:52
















                      Yes, they signal a list, but what else?
                      – Zizouz212
                      Jun 5 '15 at 15:52




                      Yes, they signal a list, but what else?
                      – Zizouz212
                      Jun 5 '15 at 15:52


















                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f30670310%2fwhat-do-brackets-in-a-for-loop-in-python-mean%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

                      What visual should I use to simply compare current year value vs last year in Power BI desktop

                      Alexandru Averescu

                      Trompette piccolo