Find index of a list where that list is part of a larger listHow do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonAccessing the index in 'for' loops?How do I remove an element from a list by index in Python?How to make a flat list out of list of lists?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?Find current directory and file's directory

Can a stoichiometric mixture of oxygen and methane exist as a liquid at standard pressure and some (low) temperature?

Why does Carol not get rid of the Kree symbol on her suit when she changes its colours?

Why can't the Brexit deadlock in the UK parliament be solved with a plurality vote?

What are some good ways to treat frozen vegetables such that they behave like fresh vegetables when stir frying them?

C++ check if statement can be evaluated constexpr

Short story about a deaf man, who cuts people tongues

Is this toilet slogan correct usage of the English language?

Why is so much work done on numerical verification of the Riemann Hypothesis?

Doesn't the system of the Supreme Court oppose justice?

Did the UK lift the requirement for registering SIM cards?

Why is the "ls" command showing permissions of files in a FAT32 partition?

Creating two special characters

Does the reader need to like the PoV character?

A variation to the phrase "hanging over my shoulders"

Change the color of a single dot in `ddot` symbol

Shouldn’t conservatives embrace universal basic income?

Has any country ever had 2 former presidents in jail simultaneously?

"It doesn't matter" or "it won't matter"?

The Digit Triangles

Does "he squandered his car on drink" sound natural?

How to make money from a browser who sees 5 seconds into the future of any web page?

Taxes on Dividends in a Roth IRA

What fields between the rationals and the reals allow a good notion of 2D distance?

Non-trope happy ending?



Find index of a list where that list is part of a larger list


How do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonAccessing the index in 'for' loops?How do I remove an element from a list by index in Python?How to make a flat list out of list of lists?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?Find current directory and file's directory













1















I have various complex lists such as



lista = [3,4,[5,[1,2],0]
listb = [[3,4],0,[1,5],2]


I need to find the position of the items in the top list. My output would be item, index for the first list:



0 3
1 2
2 2
3 0
4 1
5 2


So 5,1,2 are in position 3.



In the other list:



0 1
1 2
2 3
3 0
4 0
5 2


The number of sublists can vary and each sublist can have sublists.



In order to simplify, I have searched for any list with a "," and flatted that into 1 sublist.



I could have a list of individual elements and lists but I could not get the indexes. I also tried converting the individual elements into a single item list and appending it but I still cannot get the index of the sublist.










share|improve this question
























  • please post your code and tryings

    – Maciej S.
    Mar 8 at 0:32











  • Fix your lista, it's missing a closing bracket somewhere which makes your desired output ambiguous

    – Olivier Melançon
    Mar 8 at 12:35















1















I have various complex lists such as



lista = [3,4,[5,[1,2],0]
listb = [[3,4],0,[1,5],2]


I need to find the position of the items in the top list. My output would be item, index for the first list:



0 3
1 2
2 2
3 0
4 1
5 2


So 5,1,2 are in position 3.



In the other list:



0 1
1 2
2 3
3 0
4 0
5 2


The number of sublists can vary and each sublist can have sublists.



In order to simplify, I have searched for any list with a "," and flatted that into 1 sublist.



I could have a list of individual elements and lists but I could not get the indexes. I also tried converting the individual elements into a single item list and appending it but I still cannot get the index of the sublist.










share|improve this question
























  • please post your code and tryings

    – Maciej S.
    Mar 8 at 0:32











  • Fix your lista, it's missing a closing bracket somewhere which makes your desired output ambiguous

    – Olivier Melançon
    Mar 8 at 12:35













1












1








1








I have various complex lists such as



lista = [3,4,[5,[1,2],0]
listb = [[3,4],0,[1,5],2]


I need to find the position of the items in the top list. My output would be item, index for the first list:



0 3
1 2
2 2
3 0
4 1
5 2


So 5,1,2 are in position 3.



In the other list:



0 1
1 2
2 3
3 0
4 0
5 2


The number of sublists can vary and each sublist can have sublists.



In order to simplify, I have searched for any list with a "," and flatted that into 1 sublist.



I could have a list of individual elements and lists but I could not get the indexes. I also tried converting the individual elements into a single item list and appending it but I still cannot get the index of the sublist.










share|improve this question
















I have various complex lists such as



lista = [3,4,[5,[1,2],0]
listb = [[3,4],0,[1,5],2]


I need to find the position of the items in the top list. My output would be item, index for the first list:



0 3
1 2
2 2
3 0
4 1
5 2


So 5,1,2 are in position 3.



In the other list:



0 1
1 2
2 3
3 0
4 0
5 2


The number of sublists can vary and each sublist can have sublists.



In order to simplify, I have searched for any list with a "," and flatted that into 1 sublist.



I could have a list of individual elements and lists but I could not get the indexes. I also tried converting the individual elements into a single item list and appending it but I still cannot get the index of the sublist.







python python-2.7






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 3:38









John Kugelman

246k54406459




246k54406459










asked Mar 8 at 0:02









AmyAmy

61




61












  • please post your code and tryings

    – Maciej S.
    Mar 8 at 0:32











  • Fix your lista, it's missing a closing bracket somewhere which makes your desired output ambiguous

    – Olivier Melançon
    Mar 8 at 12:35

















  • please post your code and tryings

    – Maciej S.
    Mar 8 at 0:32











  • Fix your lista, it's missing a closing bracket somewhere which makes your desired output ambiguous

    – Olivier Melançon
    Mar 8 at 12:35
















please post your code and tryings

– Maciej S.
Mar 8 at 0:32





please post your code and tryings

– Maciej S.
Mar 8 at 0:32













Fix your lista, it's missing a closing bracket somewhere which makes your desired output ambiguous

– Olivier Melançon
Mar 8 at 12:35





Fix your lista, it's missing a closing bracket somewhere which makes your desired output ambiguous

– Olivier Melançon
Mar 8 at 12:35












2 Answers
2






active

oldest

votes


















0














You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate function to generate list indices and output them as the second item of a tuple:



def flatten(l):
return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]


so that given:



lista=[3,4,[5,[1,2]],0]
listb=[[3,4],0,[1,5],2]


the following:



print(flatten(lista))
print(flatten(listb))


will output:



[(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
[(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]


or if you prefer the output to be sorted by the item values:



print(sorted(flatten(lista)))
print(sorted(flatten(listb)))


will output:



[(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
[(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]





share|improve this answer
































    0














    You could use a function like this:



    def find_index(val, lst):
    for i, x in enumerate(lst):
    if val == x:
    return i
    elif type(x) is list: # or type(x) not in float, int
    try:
    find_index(val, x)
    # matched without error
    return i
    except ValueError:
    # not in list
    pass
    # not found
    raise ValueError(' is not in the list'.format(val))


    This uses the enumerate function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.



    Test:



    lst = [[3, 4], 0, [1, [5]], 2]
    for x in range(6):
    print x, find_index(x, lst)

    # 0 1
    # 1 2
    # 2 3
    # 3 0
    # 4 0
    # 5 2


    If you want to be able to work with any type of iterable (not just lists), you could try this more general code, but it's harder to follow:



    def find_index(val, values):
    try:
    # Search list of items
    for i, x in enumerate(values):
    try:
    find_index(val, x) # any error?
    return i # succeeded
    except ValueError:
    pass
    except TypeError:
    # not a list, just an item
    if values == val:
    return 0 # found
    # not found
    raise ValueError(' is not in the list'.format(val))





    share|improve this answer
























      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%2f55054768%2ffind-index-of-a-list-where-that-list-is-part-of-a-larger-list%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









      0














      You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate function to generate list indices and output them as the second item of a tuple:



      def flatten(l):
      return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]


      so that given:



      lista=[3,4,[5,[1,2]],0]
      listb=[[3,4],0,[1,5],2]


      the following:



      print(flatten(lista))
      print(flatten(listb))


      will output:



      [(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
      [(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]


      or if you prefer the output to be sorted by the item values:



      print(sorted(flatten(lista)))
      print(sorted(flatten(listb)))


      will output:



      [(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
      [(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]





      share|improve this answer





























        0














        You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate function to generate list indices and output them as the second item of a tuple:



        def flatten(l):
        return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]


        so that given:



        lista=[3,4,[5,[1,2]],0]
        listb=[[3,4],0,[1,5],2]


        the following:



        print(flatten(lista))
        print(flatten(listb))


        will output:



        [(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
        [(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]


        or if you prefer the output to be sorted by the item values:



        print(sorted(flatten(lista)))
        print(sorted(flatten(listb)))


        will output:



        [(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
        [(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]





        share|improve this answer



























          0












          0








          0







          You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate function to generate list indices and output them as the second item of a tuple:



          def flatten(l):
          return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]


          so that given:



          lista=[3,4,[5,[1,2]],0]
          listb=[[3,4],0,[1,5],2]


          the following:



          print(flatten(lista))
          print(flatten(listb))


          will output:



          [(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
          [(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]


          or if you prefer the output to be sorted by the item values:



          print(sorted(flatten(lista)))
          print(sorted(flatten(listb)))


          will output:



          [(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
          [(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]





          share|improve this answer















          You can use a function that flattens a given list by iterating through the list items and recursively flattens an item if it is a list. Use the enumerate function to generate list indices and output them as the second item of a tuple:



          def flatten(l):
          return [(n, i) for i, v in enumerate(l) for n, _ in (flatten(v) if isinstance(v, list) else ((v, 0),))]


          so that given:



          lista=[3,4,[5,[1,2]],0]
          listb=[[3,4],0,[1,5],2]


          the following:



          print(flatten(lista))
          print(flatten(listb))


          will output:



          [(3, 0), (4, 1), (5, 2), (1, 2), (2, 2), (0, 3)]
          [(3, 0), (4, 0), (0, 1), (1, 2), (5, 2), (2, 3)]


          or if you prefer the output to be sorted by the item values:



          print(sorted(flatten(lista)))
          print(sorted(flatten(listb)))


          will output:



          [(0, 3), (1, 2), (2, 2), (3, 0), (4, 1), (5, 2)]
          [(0, 1), (1, 2), (2, 3), (3, 0), (4, 0), (5, 2)]






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 8 at 1:35

























          answered Mar 8 at 1:07









          blhsingblhsing

          39.7k41743




          39.7k41743























              0














              You could use a function like this:



              def find_index(val, lst):
              for i, x in enumerate(lst):
              if val == x:
              return i
              elif type(x) is list: # or type(x) not in float, int
              try:
              find_index(val, x)
              # matched without error
              return i
              except ValueError:
              # not in list
              pass
              # not found
              raise ValueError(' is not in the list'.format(val))


              This uses the enumerate function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.



              Test:



              lst = [[3, 4], 0, [1, [5]], 2]
              for x in range(6):
              print x, find_index(x, lst)

              # 0 1
              # 1 2
              # 2 3
              # 3 0
              # 4 0
              # 5 2


              If you want to be able to work with any type of iterable (not just lists), you could try this more general code, but it's harder to follow:



              def find_index(val, values):
              try:
              # Search list of items
              for i, x in enumerate(values):
              try:
              find_index(val, x) # any error?
              return i # succeeded
              except ValueError:
              pass
              except TypeError:
              # not a list, just an item
              if values == val:
              return 0 # found
              # not found
              raise ValueError(' is not in the list'.format(val))





              share|improve this answer





























                0














                You could use a function like this:



                def find_index(val, lst):
                for i, x in enumerate(lst):
                if val == x:
                return i
                elif type(x) is list: # or type(x) not in float, int
                try:
                find_index(val, x)
                # matched without error
                return i
                except ValueError:
                # not in list
                pass
                # not found
                raise ValueError(' is not in the list'.format(val))


                This uses the enumerate function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.



                Test:



                lst = [[3, 4], 0, [1, [5]], 2]
                for x in range(6):
                print x, find_index(x, lst)

                # 0 1
                # 1 2
                # 2 3
                # 3 0
                # 4 0
                # 5 2


                If you want to be able to work with any type of iterable (not just lists), you could try this more general code, but it's harder to follow:



                def find_index(val, values):
                try:
                # Search list of items
                for i, x in enumerate(values):
                try:
                find_index(val, x) # any error?
                return i # succeeded
                except ValueError:
                pass
                except TypeError:
                # not a list, just an item
                if values == val:
                return 0 # found
                # not found
                raise ValueError(' is not in the list'.format(val))





                share|improve this answer



























                  0












                  0








                  0







                  You could use a function like this:



                  def find_index(val, lst):
                  for i, x in enumerate(lst):
                  if val == x:
                  return i
                  elif type(x) is list: # or type(x) not in float, int
                  try:
                  find_index(val, x)
                  # matched without error
                  return i
                  except ValueError:
                  # not in list
                  pass
                  # not found
                  raise ValueError(' is not in the list'.format(val))


                  This uses the enumerate function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.



                  Test:



                  lst = [[3, 4], 0, [1, [5]], 2]
                  for x in range(6):
                  print x, find_index(x, lst)

                  # 0 1
                  # 1 2
                  # 2 3
                  # 3 0
                  # 4 0
                  # 5 2


                  If you want to be able to work with any type of iterable (not just lists), you could try this more general code, but it's harder to follow:



                  def find_index(val, values):
                  try:
                  # Search list of items
                  for i, x in enumerate(values):
                  try:
                  find_index(val, x) # any error?
                  return i # succeeded
                  except ValueError:
                  pass
                  except TypeError:
                  # not a list, just an item
                  if values == val:
                  return 0 # found
                  # not found
                  raise ValueError(' is not in the list'.format(val))





                  share|improve this answer















                  You could use a function like this:



                  def find_index(val, lst):
                  for i, x in enumerate(lst):
                  if val == x:
                  return i
                  elif type(x) is list: # or type(x) not in float, int
                  try:
                  find_index(val, x)
                  # matched without error
                  return i
                  except ValueError:
                  # not in list
                  pass
                  # not found
                  raise ValueError(' is not in the list'.format(val))


                  This uses the enumerate function to get items and their indexes from the list. Then it tests each item directly against the required value if possible. If the item is a list, it checks that recursively instead.



                  Test:



                  lst = [[3, 4], 0, [1, [5]], 2]
                  for x in range(6):
                  print x, find_index(x, lst)

                  # 0 1
                  # 1 2
                  # 2 3
                  # 3 0
                  # 4 0
                  # 5 2


                  If you want to be able to work with any type of iterable (not just lists), you could try this more general code, but it's harder to follow:



                  def find_index(val, values):
                  try:
                  # Search list of items
                  for i, x in enumerate(values):
                  try:
                  find_index(val, x) # any error?
                  return i # succeeded
                  except ValueError:
                  pass
                  except TypeError:
                  # not a list, just an item
                  if values == val:
                  return 0 # found
                  # not found
                  raise ValueError(' is not in the list'.format(val))






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 8 at 3:29

























                  answered Mar 8 at 1:20









                  Matthias FrippMatthias Fripp

                  7,22021628




                  7,22021628



























                      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%2f55054768%2ffind-index-of-a-list-where-that-list-is-part-of-a-larger-list%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

                      Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                      Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                      How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page