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

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived