Python Forum
search a list or tuple for a specific type ot class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
search a list or tuple for a specific type ot class
#1
i can easily search a list to find the position of a specific value if i have the exact value using the index function. if i know only the type or class (an example is a search for the first float among strs and ints), is there a similarly concise way to do that search (in the hope it is super fast like list.index might be) and not have to code my own loop (which is doomed to be as slow as any other simple loop over a list). note that i want the position, not just whether some item is of that type. for example, i want the index of the first int in a tuple (or the first str in a list).
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
I don't think there's a way, by using only a list to avoid an O(n) search to do this. Could you store that data at the time you construct (and subsequently update) the list in another data structure (like a dict or whatever makes sense)?
Reply
#3
I don't think that there is a Built-in function for that, but you can create the following loop using Isinstance:

myList = [2, 5.6, "Some string"]

def find_with_type(type): # Specify Which Type to search for.
    x = 0
    for item in myList:
        if isinstance(item, type):
            return f"{myList[x]} is the first item of {type}.   It has the index {x}"
        x += 1

print(find_with_type(str)) # <-- Specify here, If you want integer, type int instead of str

# Eg:
print(find_with_type(int))
Output:
Some string is the first item of <class 'str'>. It has the index 2 2 is the first item of <class 'int'>. It has the index 0
Here are all the type classes you can use:
float, int, str, list, dict, tuple

Did you want something like this?
BashBedlam likes this post
Reply
#4
i already did something like that. i was hoping for something with more done internally for a chance to be faster in some implementation(s) of Python.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#5
(Jul-19-2022, 10:07 PM)Skaperen Wrote: i already did something like that. i was hoping for something with more done internally for a chance to be faster in some implementation(s) of Python.

Nice! But I don't think there are built-in functions for that.
Reply
#6
There should be not this kind of functions because it destroys the whole sense of duck typing.
If a list contains different types, which behaves different, then something is wrong with the code itself.

You can filter elements from a sequence easily, but better is to have objects in the list, which behaves similar (same methods, attributes etc.).
def get_type(expected_type):
    def inner(value):
        return isinstance(value, expected_type)
    return inner

my_list = [1, 2, 3, "a", 4.2, 4]
only_ints = list(filter(get_type(int), my_list))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
(Jul-21-2022, 09:01 AM)DeaD_EyE Wrote: There should be not this kind of functions because it destroys the whole sense of duck typing.
If a list contains different types, which behaves different, then something is wrong with the code itself.
if i have a list of strings and 2-tuples of 2 ints, where the 2-tuples of 2 ints change the cursor position to display the next text, that would be different behavior but is something i would consider to be valid duck typing for a list.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#8
(Jul-21-2022, 10:50 PM)Skaperen Wrote: if i have a list of strings and 2-tuples of 2 ints, where the 2-tuples of 2 ints change the cursor position to display the next text

Then try to find a better data-structure.

data = ["test1", (10, 10), "test2", (10, 20)]
This could be deconstructed into two different objects and later with zip, you can combine them:

data = ["test1", (10, 10), "test2", (10, 20)]
texts = data[::2]
positions = data[1::2]

for text, pos in zip(texts, positions):
    for _ in range(pos[1]):
        print()
    print(text.rjust(pos[0]))
As you can see, first I create the list, then deconstructing it, then zipping it.

A different data structure can solve this problem
data = [
    {"text": "test1", "position": (10, 10)},
    {"text": "test2", "position": (10, 20)},
]

for element in data:

    x, y = element["position"]
    for _ in range(y):
        print()

    print(element["text"].rjust(x))
And it's better for typing.
from typing import TypedDict


class LCD_Data(TypedDict):
    text: str
    position: tuple[int, int]


def test1(data_many: list[LCD_Data]):
    ...


def test2(data_one: LCD_Data):
    ...


data: list[LCD_Data] = [
    {"text": "test1", "position": (10, 10)},
    {"text": "test2", "position": (10, 20)},
]


# check with IDE or MyPy
test1(data)  # ok
test1(data[0])  # fail

test2(data)  # fail
test2(data[0])  # ok
Output:
[andre@andre-Fujitsu-i5 ~]$ mypy mt.py mt.py:25: error: Argument 1 to "test1" has incompatible type "LCD_Data"; expected "List[LCD_Data]" mt.py:27: error: Argument 1 to "test2" has incompatible type "List[LCD_Data]"; expected "LCD_Data" Found 2 errors in 1 file (checked 1 source file)
Even without typehints, but with the right data-sructure, you get lesser errors.
Getting the right elements from a mixed list is a bit of guessing.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#9
there are easy ways to work with mixed types as long as you have a means to check the type. one of the languages i tried back in the 1980's had mixed types but no way to check what they were. i found that language to be no better than machine language (is that 32 booleans or a pair of 16-bit ints). at least Pike had a "mixed" type that could be declared. i used that a lot.
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 468 Feb-05-2024, 01:18 PM
Last Post: deanhystad
  Search Excel File with a list of values huzzug 4 1,216 Nov-03-2023, 05:35 PM
Last Post: huzzug
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 468 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  How to read module/class from list of strings? popular_dog 1 467 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  Change font in a list or tuple apffal 4 2,670 Jun-16-2023, 02:55 AM
Last Post: schriftartenio
  search in dict inside tuple steg 1 682 Mar-29-2023, 01:15 PM
Last Post: rob101
  Use a class type in it MathisDELAGE 2 905 Jan-29-2023, 11:37 AM
Last Post: MathisDELAGE
  TypeError: unsupported opperand type(s) for %: 'int' and 'list' cool_person 7 2,139 May-07-2022, 08:40 AM
Last Post: ibreeden
  unsupported operand type(s) for %: 'list' and 'int' RandomCoder 4 32,831 May-07-2022, 08:07 AM
Last Post: menator01
  why is my list a tuple CompleteNewb 7 2,260 Mar-17-2022, 10:09 PM
Last Post: CompleteNewb

Forum Jump:

User Panel Messages

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