coolman1995
coolman1995

Reputation: 21

Pick words from list that start with a character from a list of valid characters

For the character F only:

sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
newl = []

for word in sportslist:
    if word.startswith('F'):
        newl.append(word)
        print (newl)

Output:

['Football'] , ['Fencing'] 

I used the for loop to obviously repeat the coding but for some reason when I try print out multiple words beginning with another letter, say I wanted to print out the words beginning with F and B. How would I execute that as I just get a blank output?

Upvotes: 1

Views: 93

Answers (4)

patrec
patrec

Reputation: 49

If you want to get fancy and complicate things, then you can use the filter function:

sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
letters = ('F', 'B')
new1 = list(filter(lambda item:item.startswith(letters), sportslist))
print(new1)
#['Football', 'Fencing', 'Basketball', 'Baseball']    # <-- output

Upvotes: 0

MarianD
MarianD

Reputation: 14131

You may use

  • a tuple of all accepted starting strings (as an argument of the .startswith() method),

  • (eventually) a list comprehension
    (instead of your for loop with the if statement and the .append() method):

sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]

newl = [word    for word in sportslist    if word.startswith(("F", "B"))]
print(newl)

['Football', 'Fencing', 'Basketball', 'Baseball']

Note:

I added superfluous spaces into the list comprehension to emphasize its 3 parts:

  1. word - what to add into the target list,
  2. for word in sportslist — from where is word in the point 1. iteratively obtained,
  3. if word.startswith(("F", "B")) - which condition must word from the point 2. satisfy.

Upvotes: 2

MarianD
MarianD

Reputation: 14131

You may use a tuple ('F', 'B') as an argument of the .startswith() method and correct the indentation of the last line of your code:

sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
newl = []

for word in sportslist:
    if word.startswith(('F', 'B')):
        newl.append(word)
print (newl)                         # <------------ no indentation!

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71570

You could do an or and apply another startswith for B, that would work:

for word in eustates:
    if word.startswith('F') or word.startswith('B'):
        newl.append(word)
        print (newl)

Or you could try:

for word in eustates:
    if word[:1] in 'BF':
        newl.append(word)
        print (newl)

Or:

for word in eustates:
    if 'BF'.__contains__(word[:1]):
        newl.append(word)
        print (newl)

Upvotes: 1

Related Questions