Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
in a list or tuple
#1
given an object that is in a list or tuple, is there a way to detect which type it is in?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Not directly. The object itself doesn't have knowledge of other objects that may refer to it. It may in fact be "in" tons of other objects, so it could simultaneously be in both lists and tuples. It might be "in" an object that is no longer referenced and will be garbage-collected away later.

Cpython internals have a reference count, but I'm not sure how you could access that. Even with the count, I don't think you can manipulate it to get the objects holding the reference.

You could potentially inspect all objects in your current scopes and examine them all of their contents looking for your target object, but I would look for other ways to solve the problem before attempting. How are you trying to use this information?
Reply
#3
Here's one way to go about it using try and except and then parsing the error that is returned.

tester1 = ('this', 'and', 'that')
tester2 = ['this', 'and', 'that']

def list_or_tuple (test_element) :
	try :
		test_element ['dummy']
	except TypeError as error:
		return (error.__str__ ().split (' ') [0])

print (f'tester1 [0] is "{tester1 [0]}".')
print (f'tester1 is a {list_or_tuple (tester1)}.\n')
print (f'tester2 [2] is "{tester2 [2]}".')
print (f'tester2 is a {list_or_tuple (tester2)}.')
Output:
tester1 [0] is "this". tester1 is a tuple. tester2 [2] is "that". tester2 is a list.
Reply
#4
That function reports if an object is a tuple or a list. You could that more directly via type().

tester1 = ('this', 'and', 'that')
tester2 = ['this', 'and', 'that']

print (f'tester1 is a {type(tester1).__name__}.')
print (f'tester2 is a {type(tester2).__name__}.')
Output:
tester1 is a tuple. tester2 is a list.
I interpreted the question as how do you tell what tester1 is when you don't have access to tester1 at all, just to one of the elements inside.
Reply
#5
(May-15-2021, 12:09 AM)bowlofred Wrote: How are you trying to use this information?
it is a function that is to output information about the object. it is a recursive function for references, so the caller will be dealing with the containing object, if there is one. so i just need pass that info in the call, such as another item in **kwargs.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
Could pass the parent type into the recursive function, something like the following:
def recursive_parent_obj(obj, parent_type):

    if not obj or not isinstance(obj, (list, tuple)):
        return

    if isinstance(obj[0], (list, tuple)):
        recursive_parent_obj(obj[0], type(obj[0]))
        recursive_parent_obj(obj[1:], parent_type)
    else:
        print(f'first_obj: {obj[0]}, parent_type: {parent_type}')
        recursive_parent_obj(obj[1:], parent_type)


obj = [1, 2, (11, [21, 22], 12, [31, 32], 13), 3, 4]
recursive_parent_obj(obj, type(obj))
Output:
first_obj: 1, parent_type: <class 'list'> first_obj: 2, parent_type: <class 'list'> first_obj: 11, parent_type: <class 'tuple'> first_obj: 21, parent_type: <class 'list'> first_obj: 22, parent_type: <class 'list'> first_obj: 12, parent_type: <class 'tuple'> first_obj: 31, parent_type: <class 'list'> first_obj: 32, parent_type: <class 'list'> first_obj: 13, parent_type: <class 'tuple'> first_obj: 3, parent_type: <class 'list'> first_obj: 4, parent_type: <class 'list'>
Reply
#7
(May-15-2021, 01:15 AM)BashBedlam Wrote: Here's one way
this is checking the whole list or tuple, not a contained item. i could just use type(foo).__name__

>>> a=['this','or','that']
>>> b=('this','or','that')
>>> type(a).__name__
'list'
>>> type(b).__name__
'tuple'

the real point is, the function that needed to know only had a reference to the item, not the container. but the was a called context where it mattered where the caller got the item from. the caller could have passed that along. that's the way i need to do this. the item might even be just a value like an int. the item could be in a tuple and in a list. or even a dict. or in some other kind of custom object.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  using > < for tuple , list,... akbarza 3 469 Feb-05-2024, 01:18 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 470 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Change font in a list or tuple apffal 4 2,670 Jun-16-2023, 02:55 AM
Last Post: schriftartenio
  search a list or tuple for a specific type ot class Skaperen 8 1,918 Jul-22-2022, 10:29 PM
Last Post: Skaperen
  why is my list a tuple CompleteNewb 7 2,264 Mar-17-2022, 10:09 PM
Last Post: CompleteNewb
  Create SQLite columns from a list or tuple? snakes 6 8,669 May-04-2021, 12:06 PM
Last Post: snakes
  What type of *data* is the name of a list/tuple/dict, etc? alloydog 9 4,368 Jan-30-2021, 07:11 AM
Last Post: alloydog
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 2,806 Nov-04-2020, 11:26 AM
Last Post: Aggam
  Python Error- TypeError: ('Params must be in a list, tuple, or Row', 'HY000') DarkCoder2020 3 5,571 Jul-29-2020, 12:02 AM
Last Post: Larz60+
  Arrange list of tuple using loop batchenr 7 3,479 Jun-16-2019, 03:24 PM
Last Post: Abdullah

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020