How can I find the average of a list with multiple cells?











up vote
-2
down vote

favorite












Example: x = [[1,3,2],[4,5,6],[7,8,9]]



I attempted to use:



sum(x) / len(x) but it seems to give me this error



(TypeError: unsupported operand type(s) for +: 'int' and 'list')



The list is inputted by the user with command: average_list() and could contain any amount of numbers per square brackets.










share|improve this question




















  • 2




    Do you want the average of complete list or average of lists inside list?
    – Sanchit Kumar
    Nov 11 at 0:50










  • I want the average of the complete list! Sorry for not being clear I'm a beginner to this website and Python.
    – Nima Yeganeh
    Nov 11 at 0:51










  • Also, sum does not work on list of lists, it only adds level 1 sub elements.
    – Rocky Li
    Nov 11 at 0:51















up vote
-2
down vote

favorite












Example: x = [[1,3,2],[4,5,6],[7,8,9]]



I attempted to use:



sum(x) / len(x) but it seems to give me this error



(TypeError: unsupported operand type(s) for +: 'int' and 'list')



The list is inputted by the user with command: average_list() and could contain any amount of numbers per square brackets.










share|improve this question




















  • 2




    Do you want the average of complete list or average of lists inside list?
    – Sanchit Kumar
    Nov 11 at 0:50










  • I want the average of the complete list! Sorry for not being clear I'm a beginner to this website and Python.
    – Nima Yeganeh
    Nov 11 at 0:51










  • Also, sum does not work on list of lists, it only adds level 1 sub elements.
    – Rocky Li
    Nov 11 at 0:51













up vote
-2
down vote

favorite









up vote
-2
down vote

favorite











Example: x = [[1,3,2],[4,5,6],[7,8,9]]



I attempted to use:



sum(x) / len(x) but it seems to give me this error



(TypeError: unsupported operand type(s) for +: 'int' and 'list')



The list is inputted by the user with command: average_list() and could contain any amount of numbers per square brackets.










share|improve this question















Example: x = [[1,3,2],[4,5,6],[7,8,9]]



I attempted to use:



sum(x) / len(x) but it seems to give me this error



(TypeError: unsupported operand type(s) for +: 'int' and 'list')



The list is inputted by the user with command: average_list() and could contain any amount of numbers per square brackets.







python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 0:49









Rocky Li

2,4781315




2,4781315










asked Nov 11 at 0:48









Nima Yeganeh

31




31








  • 2




    Do you want the average of complete list or average of lists inside list?
    – Sanchit Kumar
    Nov 11 at 0:50










  • I want the average of the complete list! Sorry for not being clear I'm a beginner to this website and Python.
    – Nima Yeganeh
    Nov 11 at 0:51










  • Also, sum does not work on list of lists, it only adds level 1 sub elements.
    – Rocky Li
    Nov 11 at 0:51














  • 2




    Do you want the average of complete list or average of lists inside list?
    – Sanchit Kumar
    Nov 11 at 0:50










  • I want the average of the complete list! Sorry for not being clear I'm a beginner to this website and Python.
    – Nima Yeganeh
    Nov 11 at 0:51










  • Also, sum does not work on list of lists, it only adds level 1 sub elements.
    – Rocky Li
    Nov 11 at 0:51








2




2




Do you want the average of complete list or average of lists inside list?
– Sanchit Kumar
Nov 11 at 0:50




Do you want the average of complete list or average of lists inside list?
– Sanchit Kumar
Nov 11 at 0:50












I want the average of the complete list! Sorry for not being clear I'm a beginner to this website and Python.
– Nima Yeganeh
Nov 11 at 0:51




I want the average of the complete list! Sorry for not being clear I'm a beginner to this website and Python.
– Nima Yeganeh
Nov 11 at 0:51












Also, sum does not work on list of lists, it only adds level 1 sub elements.
– Rocky Li
Nov 11 at 0:51




Also, sum does not work on list of lists, it only adds level 1 sub elements.
– Rocky Li
Nov 11 at 0:51












6 Answers
6






active

oldest

votes

















up vote
0
down vote



accepted










You can sum the sums of the inner lists:



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

s = sum(sum(a) for a in x)
l = sum(len(a) for a in x)
print(s / l) # 5.0





share|improve this answer





















  • This is working, but how would you return 0 if the user left the input empty perhaps? For example x =
    – Nima Yeganeh
    Nov 11 at 1:06












  • @NimaYeganeh you can check if len(x) == 0. If it is, return 0, otherwise, return the average.
    – slider
    Nov 11 at 1:09


















up vote
0
down vote













Use numpy



import numpy as np

x = np.array(x)
avg = np.sum(x)/np.size(x) # avg = 5





share|improve this answer





















  • Why not use numpy's mean method? np.array(x).mean()
    – Bill
    Nov 11 at 1:23


















up vote
0
down vote













x = [i for sublist in x for i in sublist]
avg = sum(x)/len(x)


Here is an answer after flattening the list






share|improve this answer




























    up vote
    0
    down vote













    This provides you both, the average of the lists of list as well as the average of complete list.



    x = [[1,3,2],[4,5,6],[7,8,9]]
    new_list = [sum(l)/len(l) for l in x]
    print(sum(new_list)/len(new_list))


    Output:



    5.0





    share|improve this answer




























      up vote
      0
      down vote













      A more scholastic way to do this is the following:



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

      #stripping square brackets
      elementsString = ''.join( c for c in str(x) if c not in '' )

      total = 0
      numberOfElements = 0

      #converting the string numbers into int
      for i in elementsString.split(','):
      #using int but can be also float for example
      i = int(i)
      numberOfElements += 1
      total += i

      average = total/numberOfElements
      print(average)

      #5.0 is the answer in your case





      share|improve this answer




























        up vote
        -2
        down vote













        are you trying to find the average of the sum of the entire list of (x) or the sum of each cell?






        share|improve this answer





















        • Trying to find the average of the sum of the entire list.
          – Nima Yeganeh
          Nov 11 at 0:53










        • @isaac Please ask the clarifications in the comment section.
          – Sanchit Kumar
          Nov 11 at 0:57











        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%2f53244856%2fhow-can-i-find-the-average-of-a-list-with-multiple-cells%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        0
        down vote



        accepted










        You can sum the sums of the inner lists:



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

        s = sum(sum(a) for a in x)
        l = sum(len(a) for a in x)
        print(s / l) # 5.0





        share|improve this answer





















        • This is working, but how would you return 0 if the user left the input empty perhaps? For example x =
          – Nima Yeganeh
          Nov 11 at 1:06












        • @NimaYeganeh you can check if len(x) == 0. If it is, return 0, otherwise, return the average.
          – slider
          Nov 11 at 1:09















        up vote
        0
        down vote



        accepted










        You can sum the sums of the inner lists:



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

        s = sum(sum(a) for a in x)
        l = sum(len(a) for a in x)
        print(s / l) # 5.0





        share|improve this answer





















        • This is working, but how would you return 0 if the user left the input empty perhaps? For example x =
          – Nima Yeganeh
          Nov 11 at 1:06












        • @NimaYeganeh you can check if len(x) == 0. If it is, return 0, otherwise, return the average.
          – slider
          Nov 11 at 1:09













        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        You can sum the sums of the inner lists:



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

        s = sum(sum(a) for a in x)
        l = sum(len(a) for a in x)
        print(s / l) # 5.0





        share|improve this answer












        You can sum the sums of the inner lists:



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

        s = sum(sum(a) for a in x)
        l = sum(len(a) for a in x)
        print(s / l) # 5.0






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 11 at 0:53









        slider

        7,1051129




        7,1051129












        • This is working, but how would you return 0 if the user left the input empty perhaps? For example x =
          – Nima Yeganeh
          Nov 11 at 1:06












        • @NimaYeganeh you can check if len(x) == 0. If it is, return 0, otherwise, return the average.
          – slider
          Nov 11 at 1:09


















        • This is working, but how would you return 0 if the user left the input empty perhaps? For example x =
          – Nima Yeganeh
          Nov 11 at 1:06












        • @NimaYeganeh you can check if len(x) == 0. If it is, return 0, otherwise, return the average.
          – slider
          Nov 11 at 1:09
















        This is working, but how would you return 0 if the user left the input empty perhaps? For example x =
        – Nima Yeganeh
        Nov 11 at 1:06






        This is working, but how would you return 0 if the user left the input empty perhaps? For example x =
        – Nima Yeganeh
        Nov 11 at 1:06














        @NimaYeganeh you can check if len(x) == 0. If it is, return 0, otherwise, return the average.
        – slider
        Nov 11 at 1:09




        @NimaYeganeh you can check if len(x) == 0. If it is, return 0, otherwise, return the average.
        – slider
        Nov 11 at 1:09












        up vote
        0
        down vote













        Use numpy



        import numpy as np

        x = np.array(x)
        avg = np.sum(x)/np.size(x) # avg = 5





        share|improve this answer





















        • Why not use numpy's mean method? np.array(x).mean()
          – Bill
          Nov 11 at 1:23















        up vote
        0
        down vote













        Use numpy



        import numpy as np

        x = np.array(x)
        avg = np.sum(x)/np.size(x) # avg = 5





        share|improve this answer





















        • Why not use numpy's mean method? np.array(x).mean()
          – Bill
          Nov 11 at 1:23













        up vote
        0
        down vote










        up vote
        0
        down vote









        Use numpy



        import numpy as np

        x = np.array(x)
        avg = np.sum(x)/np.size(x) # avg = 5





        share|improve this answer












        Use numpy



        import numpy as np

        x = np.array(x)
        avg = np.sum(x)/np.size(x) # avg = 5






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 11 at 0:53









        Rocky Li

        2,4781315




        2,4781315












        • Why not use numpy's mean method? np.array(x).mean()
          – Bill
          Nov 11 at 1:23


















        • Why not use numpy's mean method? np.array(x).mean()
          – Bill
          Nov 11 at 1:23
















        Why not use numpy's mean method? np.array(x).mean()
        – Bill
        Nov 11 at 1:23




        Why not use numpy's mean method? np.array(x).mean()
        – Bill
        Nov 11 at 1:23










        up vote
        0
        down vote













        x = [i for sublist in x for i in sublist]
        avg = sum(x)/len(x)


        Here is an answer after flattening the list






        share|improve this answer

























          up vote
          0
          down vote













          x = [i for sublist in x for i in sublist]
          avg = sum(x)/len(x)


          Here is an answer after flattening the list






          share|improve this answer























            up vote
            0
            down vote










            up vote
            0
            down vote









            x = [i for sublist in x for i in sublist]
            avg = sum(x)/len(x)


            Here is an answer after flattening the list






            share|improve this answer












            x = [i for sublist in x for i in sublist]
            avg = sum(x)/len(x)


            Here is an answer after flattening the list







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 11 at 0:53









            leeym

            312213




            312213






















                up vote
                0
                down vote













                This provides you both, the average of the lists of list as well as the average of complete list.



                x = [[1,3,2],[4,5,6],[7,8,9]]
                new_list = [sum(l)/len(l) for l in x]
                print(sum(new_list)/len(new_list))


                Output:



                5.0





                share|improve this answer

























                  up vote
                  0
                  down vote













                  This provides you both, the average of the lists of list as well as the average of complete list.



                  x = [[1,3,2],[4,5,6],[7,8,9]]
                  new_list = [sum(l)/len(l) for l in x]
                  print(sum(new_list)/len(new_list))


                  Output:



                  5.0





                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    This provides you both, the average of the lists of list as well as the average of complete list.



                    x = [[1,3,2],[4,5,6],[7,8,9]]
                    new_list = [sum(l)/len(l) for l in x]
                    print(sum(new_list)/len(new_list))


                    Output:



                    5.0





                    share|improve this answer












                    This provides you both, the average of the lists of list as well as the average of complete list.



                    x = [[1,3,2],[4,5,6],[7,8,9]]
                    new_list = [sum(l)/len(l) for l in x]
                    print(sum(new_list)/len(new_list))


                    Output:



                    5.0






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 11 at 0:56









                    Sanchit Kumar

                    31117




                    31117






















                        up vote
                        0
                        down vote













                        A more scholastic way to do this is the following:



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

                        #stripping square brackets
                        elementsString = ''.join( c for c in str(x) if c not in '' )

                        total = 0
                        numberOfElements = 0

                        #converting the string numbers into int
                        for i in elementsString.split(','):
                        #using int but can be also float for example
                        i = int(i)
                        numberOfElements += 1
                        total += i

                        average = total/numberOfElements
                        print(average)

                        #5.0 is the answer in your case





                        share|improve this answer

























                          up vote
                          0
                          down vote













                          A more scholastic way to do this is the following:



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

                          #stripping square brackets
                          elementsString = ''.join( c for c in str(x) if c not in '' )

                          total = 0
                          numberOfElements = 0

                          #converting the string numbers into int
                          for i in elementsString.split(','):
                          #using int but can be also float for example
                          i = int(i)
                          numberOfElements += 1
                          total += i

                          average = total/numberOfElements
                          print(average)

                          #5.0 is the answer in your case





                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            A more scholastic way to do this is the following:



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

                            #stripping square brackets
                            elementsString = ''.join( c for c in str(x) if c not in '' )

                            total = 0
                            numberOfElements = 0

                            #converting the string numbers into int
                            for i in elementsString.split(','):
                            #using int but can be also float for example
                            i = int(i)
                            numberOfElements += 1
                            total += i

                            average = total/numberOfElements
                            print(average)

                            #5.0 is the answer in your case





                            share|improve this answer












                            A more scholastic way to do this is the following:



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

                            #stripping square brackets
                            elementsString = ''.join( c for c in str(x) if c not in '' )

                            total = 0
                            numberOfElements = 0

                            #converting the string numbers into int
                            for i in elementsString.split(','):
                            #using int but can be also float for example
                            i = int(i)
                            numberOfElements += 1
                            total += i

                            average = total/numberOfElements
                            print(average)

                            #5.0 is the answer in your case






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 11 at 1:39









                            Antonino

                            1,25211224




                            1,25211224






















                                up vote
                                -2
                                down vote













                                are you trying to find the average of the sum of the entire list of (x) or the sum of each cell?






                                share|improve this answer





















                                • Trying to find the average of the sum of the entire list.
                                  – Nima Yeganeh
                                  Nov 11 at 0:53










                                • @isaac Please ask the clarifications in the comment section.
                                  – Sanchit Kumar
                                  Nov 11 at 0:57















                                up vote
                                -2
                                down vote













                                are you trying to find the average of the sum of the entire list of (x) or the sum of each cell?






                                share|improve this answer





















                                • Trying to find the average of the sum of the entire list.
                                  – Nima Yeganeh
                                  Nov 11 at 0:53










                                • @isaac Please ask the clarifications in the comment section.
                                  – Sanchit Kumar
                                  Nov 11 at 0:57













                                up vote
                                -2
                                down vote










                                up vote
                                -2
                                down vote









                                are you trying to find the average of the sum of the entire list of (x) or the sum of each cell?






                                share|improve this answer












                                are you trying to find the average of the sum of the entire list of (x) or the sum of each cell?







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Nov 11 at 0:52









                                isaac fuller

                                263




                                263












                                • Trying to find the average of the sum of the entire list.
                                  – Nima Yeganeh
                                  Nov 11 at 0:53










                                • @isaac Please ask the clarifications in the comment section.
                                  – Sanchit Kumar
                                  Nov 11 at 0:57


















                                • Trying to find the average of the sum of the entire list.
                                  – Nima Yeganeh
                                  Nov 11 at 0:53










                                • @isaac Please ask the clarifications in the comment section.
                                  – Sanchit Kumar
                                  Nov 11 at 0:57
















                                Trying to find the average of the sum of the entire list.
                                – Nima Yeganeh
                                Nov 11 at 0:53




                                Trying to find the average of the sum of the entire list.
                                – Nima Yeganeh
                                Nov 11 at 0:53












                                @isaac Please ask the clarifications in the comment section.
                                – Sanchit Kumar
                                Nov 11 at 0:57




                                @isaac Please ask the clarifications in the comment section.
                                – Sanchit Kumar
                                Nov 11 at 0:57


















                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244856%2fhow-can-i-find-the-average-of-a-list-with-multiple-cells%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

                                Florida Star v. B. J. F.

                                Danny Elfman

                                Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues