Python Forum
Find not working properly
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Find not working properly
#1
Hi,
A friend is mentoring me on python (thus the world list we are using)

My challenge is in 1 line code to find all the words that have s in them.

I am fairly new to list comprehensions but are starting to get them. At my level, right now, what works best is actually writing out the logic in 2 or 3 lines then once i see it written down turning that into a list comprehension.

My question is why is find returning leon in this challenge and not sucks?

original_list = ['leon', 'sucks', 'mikes', 'balls']
for x in original_list:
    if x.find('s'): 
leon
mikes
balls
Reply
#2
You should use the in operator.
The in operator looks up, if an object appears in a sequence.
In [26]: 's' in 'Andre'
Out[26]: False

In [27]: 's' in 'Sandra'
Out[27]: False

In [28]: 's' in 'Sandra'.lower()
Out[28]: True
With a list:
In [29]: l = [1,2,3]

In [30]: 5 in l
Out[30]: False

In [31]: 1 in l
Out[31]: True
With filter:
In [32]: list(filter(lambda x: 's' in x.lower(), ['Leon', 'Sucks', 'Mikes', 'Balls']))
Out[32]: ['Sucks', 'Mikes', 'Balls']
If you have one finite list and want to have a second list multiplied by 2, you should use a list comprehension:
list1 = [1,2,3]
list2 = [i*2 for i in list1]
You can use conditions in a list comprehension:
list1 = list(range(100))
list2 = [i*2 for i in list1 if i % 2 != 0]
I think the to filter with a list comprehension looks very natural and reads like an english sentence.
name for name in A_SEQUENCE if 's' in name.lower
In [33]: [name for name in ['Leon', 'Sucks', 'Mikes', 'Balls'] if 's' in name.lower()]
Out[33]: ['Sucks', 'Mikes', 'Balls']
The list-, set-, dict comprehension and generator expressions are very helpful.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
This last post was amazing and just explained so much. Just added it to my evernote notes.

Thank you!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Enigma Program not working properly npd29 3 2,038 May-01-2020, 10:37 AM
Last Post: pyzyx3qwerty
  Printing a number sequence not working properly deepsen 6 2,947 Oct-12-2019, 07:43 PM
Last Post: deepsen

Forum Jump:

User Panel Messages

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