38
loading...
This website collects cookies to deliver better user experience
"Code is read more often than it is written"
Guido Van Rossum (Creator of Python)
players = [{'name': 'P V Sindhu', 'country': 'India'},
{'name': 'Michael Phelps', 'country': 'USA'},
{'name': 'Usain Bolt', 'country': 'Jamaica'},
{'name': 'Manika Batra', 'country': 'India'}]
indian_players = []
for player in players:
if player['country'] == 'India':
indian_players.append(player)
indian_players = [player for player in players if player['country'] == 'India']
list comprehension
we can write more expressible code.names = ['P V Sindhu', 'Usain Bolt', 'Michael Phelps', 'Manika Batra']
for i in range(len(names)):
print(names[i])
for name in names:
print(name)
for i in range(len(names)):
print(i+1, names[i])
for idx, name in enumerate(names, start=1):
print(idx, name)
names
was not a list
but a dictionary
, or some other data structure where indexing is not possible?General rule of thumb, if you are using indices for iteration, Python may have already provided some better abstractions for it.
turing_award_winners = {1966: 'Alan Perlis',
1967: 'Maurice Wilkes',
1968: 'Richard Hamming',
1969: 'Marvin Minsky'}
for year in turing_award_winners:
print(year, turing_award_winners[year])
for year, name in turing_award_winners.items():
print(year, name)
nums = [1, 5, 11, 17, 23, 29]
ans = 0
for num in nums:
ans += num
ans = sum(nums)
ans
contains the sum of all numbers in the list nums
, and is also very concise.