Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in python, using in, get specific elements

Tags:

python

list

I want to do something like this, but in python :

select * from [list] where [element at index n] = 'hello'

So far, I have this

    cells = [' ','hello',' ',' ',' ',' ',' ',' ',' ']
    emptySpots = []

    for s in range(len(cells)):
        if cells[s] == 'hello':
            emptySpots.append(s)

This gives me a list of the indexes of the cells with 'hello' in them, but I bet theres a more straightforeward (pythonesque) way to do this.

What would be nice is a one liner that just returns the count of the number of elements in cells that equal ' '.

like image 252
jason Avatar asked Mar 03 '26 03:03

jason


2 Answers

Your question is confusing. Your code does not get the indexes of the empty cells but of the element hello.

It seems you have two questions in one?

If you really want to get the number of "empty cells" like you claim in your last sentence, you can use list.count:

empty_spots = cells.count(' ')
like image 168
Felix Kling Avatar answered Mar 04 '26 17:03

Felix Kling


I wasn't sure if you wanted to return a list of matching elements from a list (the title being "in python, using in, get specific elements"), or if you wanted to count all occurrences of them. You can use filter or a list comprehension to return matching elements from a list, and then call len on the result to count the number of times it occurs. If all you care about is finding the number of times an item occurs in a list list.count is the best approach.

len(filter(lambda x: 'hello' == x, cells))

len([x for x in cells if x == 'hello'])

And as answered here (definitely the nicest way if you just wanted to count them!): cells.count(' ')

Here's a simple bench of list comprehension vs filter:

% python -m timeit -s "data = ['hello' for x in range(100000)]" "[x for x in data if x == 'hello']"
100 loops, best of 3: 6.97 msec per loop
% python -m timeit -s "data = ['hello' for x in range(100000)]" "filter(lambda x: x == 'hello', data)"
100 loops, best of 3: 13.3 msec per loop
like image 26
zeekay Avatar answered Mar 04 '26 18:03

zeekay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!