[Tutor] (no subject)

Joel Goldstick joel.goldstick at gmail.com
Tue Feb 11 06:27:24 EST 2020


On Tue, Feb 11, 2020 at 4:19 AM Akash Mudgil <mudgilakash66 at gmail.com> wrote:
>
> Let's say if you wanted to search for a username in a, list where
> 'username' variable is predefined.
>
> Example:
>
>
> username='BOB'
>
> usernames=['BOB','Alice','David']
>
> for i in range(len(usernames)):
> if usernames[i]==username:
> print("User exists in the list")
>
> This program doea a linear search on every index in the list, and if the
> value matches, returns the output. The len function gets the total length
> of the list, and the range function defines the scope of the search from
> beginning to end of the list.
>
> Hope this helps.

While the above method might work, it is a very convoluted way to use
python.  Finding the length of the list and iterating over the indices
is not pythonic.  Using the 'if name in names' construct is much more
in the spirit of the language, because it doesn't need the user to
think about indexes and lengths, which are artifacts, not the
information wanted
>
> On Tue, 11 Feb, 2020, 1:27 AM Mats Wichmann, <mats at wichmann.us> wrote:
>
> > On 2/10/20 12:36 PM, Alfie Lee wrote:
> > >
> > >
> > > Sent from Mail<https://go.microsoft.com/fwlink/?LinkId=550986> for
> > Windows 10
> > >
> > > If say I had a variable called ‘username’, and a list of usernames
> > called ‘usernames’; how would I write it so that the programme will check
> > if that username is in the usernames list?
> > > this would be using an if statement if possible.
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > To unsubscribe or change subscription options:
> > > https://mail.python.org/mailman/listinfo/tutor
> > >
> >
> >
> > if username in usernames:
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays


More information about the Tutor mailing list