Example: I created a list named months of the months of the year. How do I write a for loop that iterates over the elements of months and prints out each one that begins with letter āJā, one month per line.
Asked
Active
Viewed 2,372 times
4 Answers
1
In python you can iterate over a list using a for loop. You can then have a conditional statement that checks if the month begins with 'J'. Example:
months = ['January', 'February', 'March' 'June', 'October']
for month in months:
if month[0] == 'J':
print(month)
This results in
January
June

dennissv
- 756
- 5
- 12
0
You can use .startswith()
[print(i) for i in months if (i.lower()).startswith('j')]
Or
months = ['January', 'July', 'Nov']
for i in months:
i = i.lower()
if (i.lower()).startswith('j'):
print(i)
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 example.py January July

vash_the_stampede
- 4,590
- 1
- 8
- 20
0
If you're looking for how to filter elements out based on their initial letter this should help: Checking whether a string starts with XXXX
months=["January","February","March","April","May","June","July","August","September","October","November","December"]
for m in months:
if m.startswith('J'):
print m
January
June
July

Peybae
- 1,093
- 14
- 25
0
Iterate through each element and see if its a string. If it is, then check the first element.
yourList = ["January"]
checkLetter = "J"
for element in yourList:
if isinstance(element,str):
if element[0]== checkLetter:
print(element)