473,837 Members | 1,888 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find Items & Indices In A List...

Hello NG,

I was wondering if there is a faster/nicer method (than a for loop)
that will allow me to find the elements (AND their indices) in a list that
verify a certain condition. For example, assuming that I have a list like:

mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]

I would like to find the indices of the elements in the list that are equal
to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily
use a for loop but I was wondering if there is a faster method...

Thanks for every suggestion.

Andrea.
------------------------------------------------------------------------------------------------------------------------------------------
Message for the recipient only, if received in error, please notify the
sender and read http://www.eni.it/disclaimer/
Jul 18 '05 #1
5 2136
<an***********@ agip.it> a écrit dans le message de news:
ma************* *************** **...*@pyth on.org...
For example, assuming that I have a list like:

mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]

I would like to find the indices of the elements in the list that are
equal
to 1 (in this case, the 1,2,3,4,9 elements are equal to 1).


List comprehension is your friend:

PythonWin 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on
win32.
Portions Copyright 1994-2004 Mark Hammond (mh******@skipp inet.com.au) - see
'Help/About PythonWin' for further copyright information.
mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]
[i for i, j in enumerate(mylis t) if j==1] [1, 2, 3, 4, 9]


Jul 18 '05 #2
an***********@a gip.it wrote:
Hello NG,

I was wondering if there is a faster/nicer method (than a for loop)
that will allow me to find the elements (AND their indices) in a list that
verify a certain condition. For example, assuming that I have a list like:

mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]

I would like to find the indices of the elements in the list that are equal
to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily
use a for loop but I was wondering if there is a faster method...

Thanks for every suggestion.

Andrea.
------------------------------------------------------------------------------------------------------------------------------------------
Message for the recipient only, if received in error, please notify the
sender and read http://www.eni.it/disclaimer/


You could do a list comprehension /generator expression. Like this:
[i for i in range(len(mylis t)) if mylist[i] == 1]

--
--------------------------------------
Ola Natvig <ol********@inf osense.no>
infoSense AS / development
Jul 18 '05 #3
On Fri, 10 Dec 2004 16:01:26 +0100, an***********@a gip.it wrote:
Hello NG,

I was wondering if there is a faster/nicer method (than a for loop)
that will allow me to find the elements (AND their indices) in a list that
verify a certain condition. For example, assuming that I have a list like:

mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]

I would like to find the indices of the elements in the list that are equal
to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily
use a for loop but I was wondering if there is a faster method...

Thanks for every suggestion.

One way:
mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]
[i for i,v in enumerate(mylis t) if v==1]

[1, 2, 3, 4, 9]

Regards,
Bengt Richter
Jul 18 '05 #4
an***********@a gip.it wrote:
Hello NG,

I was wondering if there is a faster/nicer method (than a for loop)
that will allow me to find the elements (AND their indices) in a list that
verify a certain condition. For example, assuming that I have a list like:

mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]

I would like to find the indices of the elements in the list that are equal
to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily
use a for loop but I was wondering if there is a faster method...


Everyone has already given you the answer (enumerate in a LC or GE), I'd
just comment that it's easy enough to extend their answers to any given
condition:
def getindices(sequ ence, predicate): .... return [i for i, v in enumerate(seque nce) if predicate(v)]
.... getindices([0,1,1,1,1,5,6,7 ,8,1,10], bool) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def equalsone(v): .... return v == 1
.... getindices([0,1,1,1,1,5,6,7 ,8,1,10], equalsone) [1, 2, 3, 4, 9] def f(v): .... return pow(v, 3, 4) == 3
.... getindices([0,1,1,1,1,5,6,7 ,8,1,10], f)

[7]

Steve
Jul 18 '05 #5
On Fri, 10 Dec 2004 16:27:29 GMT, Steven Bethard <st************ @gmail.com> wrote:
an***********@ agip.it wrote:
Hello NG,

I was wondering if there is a faster/nicer method (than a for loop)
that will allow me to find the elements (AND their indices) in a list that
verify a certain condition. For example, assuming that I have a list like:

mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]

I would like to find the indices of the elements in the list that are equal
to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily
use a for loop but I was wondering if there is a faster method...


Everyone has already given you the answer (enumerate in a LC or GE), I'd
just comment that it's easy enough to extend their answers to any given
condition:
def getindices(sequ ence, predicate):... return [i for i, v in enumerate(seque nce) if predicate(v)]
... getindices([0,1,1,1,1,5,6,7 ,8,1,10], bool)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def equalsone(v):... return v == 1
... getindices([0,1,1,1,1,5,6,7 ,8,1,10], equalsone)[1, 2, 3, 4, 9] def f(v):... return pow(v, 3, 4) == 3
... getindices([0,1,1,1,1,5,6,7 ,8,1,10], f)

[7]

Conclusion:
Python is programmer's Lego ;-)

Regards,
Bengt Richter
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
1545
by: SnuSnu | last post by:
Okay - here's a (probably) really easy question: I can't do the following, so what's the best way to handle this case of wanting to delete within a loop? x = deletion_list = for i in deletion_list: del x
5
1824
by: Steven Bethard | last post by:
So, I have a list of lists, where the items in each sublist are of basically the same form. It looks something like: py> data = , .... .... , .... .... ] Now, I'd like to sample down the number of items in each sublist in the
2
1326
by: Steven Bethard | last post by:
Nick Coghlan wrote: > Hmm, it might be nice if there was a UserList.ListMixin that was the > counterpart to UserDict.DictMixin I've thought this occasionally too. One of the tricky issues though is that often you'd like to define __getitem__ for single items and have ListMixin add the code for slices. I haven't figured out how to do this cleanly yet... STeVe
8
1603
by: Steven Bethard | last post by:
I have a list of strings that looks something like: lst = The parentheses in the labels indicate where an "annotation" starts and ends. So for example, the label '(*)' at index 2 of the list means that I have an annotation at (2, 2), and the labels '(*', '*', '(*', '*))' at indices 4 through 7 mean that I have an annotation at (4, 7) and an annotation at (6, 7).
108
6485
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the /start/ and /stop/ indices and the /step/ or stride length of the slice. Missing or out-of-bounds indices are handled in a manner...
5
10093
by: Phill W. | last post by:
(VB'2003) What's the correct way to remove multiple, selected items from a ListView control (say, from a ContextMenu)? I ask because I'm getting a very annoying ArgumentOutOfRangeException because the ListView seems to be trying to "re-select" items that are no longer there! for example, giventhat I have 3 items in my list: Select the first and remove it - no problem.
1
4221
by: vmoreau | last post by:
I have a text and I need to find a Word that are not enclosed in paranthesis. Can it be done with a regex? Is someone could help me? I am not familar with regex... Example looking for WORD: (there is a WORD in ( my string WORD )) and * WORD * to (find WORD) and * WORD * Should give me the to word between star (star ar not part of string)
10
3927
by: Johny | last post by:
I need to find all the same words in a text . What would be the best idea to do that? I used string.find but it does not work properly for the words. Let suppose I want to find a number 324 in the text '45 324 45324' there is only one occurrence of 324 word but string.find() finds 2 occurrences ( in 45324 too)
0
1217
chathura86
by: chathura86 | last post by:
hi, i want to remove selected items from a list box this is the code i'v used Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click, lstSelNum.DoubleClick For Each i As Integer In lstSelNum.SelectedIndices txtSearch.Text += i & " - " lstSelNum.Items.RemoveAt(i)
0
9846
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9686
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10890
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10581
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10634
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9416
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7819
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4479
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3127
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.