Reputation: 23
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
for continent in continents:
print(continent)
if continent[0] == 'A':
print(continent)
This is my code that I have used. Could someone see if there is a way to print out the continents that only begin with the letter "A"?
Upvotes: 2
Views: 255
Reputation: 300
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
aNamedContinents = c
for c in continents:
if c.startswith('A'):
print(c)
Upvotes: 0
Reputation: 1
Use an if statement inside the for loop:
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
for continent in continents:
if continent[0] == 'A':
print(continent)
Upvotes: -1
Reputation: 21914
There are many ways to do this:
[continent for continent in continents if continent.startswith('A')]
(continent for continent in continents if continent.startswith('A'))
filter(lambda x: x.startswith('A'), continents)
2 and 3 is light on on memory - you can use it if you have a data-set that is really huge. 3 is a functional way of writing the same thing.
Upvotes: 4
Reputation: 524
Code using while loop with elapsed time(Time taken by code to execute task)
from datetime import datetime
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
i = 0
continent = sorted(continents)
start_time = datetime.now().time().microsecond
while i < len(continent):
if (continent[i][0] == 'A'):
print(continent[i])
i = i + 1
else:
break
end_time = datetime.now().time().microsecond
print('Time taken :', end_time - start_time, 'ms')
OutPut:-
Africa
Antarctica
Asia
Australia
Time taken : 45 ms
Upvotes: 1
Reputation: 6331
Do it like that:
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
a_continents = [c for c in continents if c.startswith('A')]
# Or:
# a_continents = [c for c in continents if c and c[0] == 'A']
print(a_continents)
Upvotes: 1
Reputation: 1095
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
for continent in continents:
if continent[0] == 'A':
print(continent)
Asia
Africa
Antarctica
Australia
Upvotes: 1
Reputation: 170
Use startswith()
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
for continent in continents:
if continent.startswith('A'):
print(continent)
Upvotes: 6
Reputation: 399
just indent the if
in order for it being inside the loop. (because we want the for
loop to go through the list and check for every element if it starts with 'A')
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
for continent in continents:
if continent[0] == 'A':
print(continent)
Upvotes: 2