user16375265
user16375265

Reputation:

Get index of letter in word in list - python

I have a long list with a lot of words and I want to create new list with just the words that start with "a".

list_1 = []

for i in range(len(words) - 1):
    if words[0: len(words) - 1][0] == "a":
        list_1.append(words)

print(list_1)

Upvotes: 0

Views: 143

Answers (5)

Tanish Sarmah
Tanish Sarmah

Reputation: 486

Check this out


for i in range(len(words) - 1):
    if words[0] == "a":
        list_1.append(words)

print(list_1)

Upvotes: 0

Bhavesh Achhada
Bhavesh Achhada

Reputation: 323

old_list = ['hello', 'world', 'alike', 'algorithm']
new_list = [i for i in old_list if i.startswith('a')]

Now printing the new_list will give ['alike', 'algorithm']

Upvotes: 0

Ashish M J
Ashish M J

Reputation: 700

Method 1 -

list_1 = []

for i in range(len(words) - 1):
    if words[i][0] == "a":
        list_1.append(words)

print(list_1)

Method 2

list_1= [word for i in words if word[0] =='a']

Upvotes: 0

user15801675
user15801675

Reputation:

You can use startswith

list_1 = [x for x in words if x.startswith('a')]

Upvotes: 3

mohamadmansourx
mohamadmansourx

Reputation: 539

Try:

list_1= [word for word in words if word[0] =='a']

Upvotes: 2

Related Questions