I am new to programming and am having trouble figuring out how to loop over a list within a list using Python.
I am working with output from the U.S. Census API that is formatted as follows:
[['NAME', 'POP_2020', 'POP_2021', 'state'],
['Oklahoma', '3962031', '3986639', '40'],
['Nebraska', '1961455', '1963692', '31'],
['Hawaii', '1451911', '1441553', '15'],
['South Dakota', '887099', '895376', '46'],
['Tennessee', '6920119', '6975218', '47']]
I would like to write a function that will extract the state name from each of the individual lists.
Here is my code:
import requests
url = f'https://api.census.gov/data/2021/pep/populationget=NAME,POP_2020,POP_2021&for=state:*'
response = requests.get(url)
data = response.json()
def statenames():
for i in data:
print(data[0])
The function above returns the following output, which isn't what I'm looking for:
['NAME', 'POP_2020', 'POP_2021', 'state']
['NAME', 'POP_2020', 'POP_2021', 'state']
['NAME', 'POP_2020', 'POP_2021', 'state']
['NAME', 'POP_2020', 'POP_2021', 'state']
['NAME', 'POP_2020', 'POP_2021', 'state']
['NAME', 'POP_2020', 'POP_2021', 'state']
['NAME', 'POP_2020', 'POP_2021', 'state']
['NAME', 'POP_2020', 'POP_2021', 'state']
I've been able to get the individual state names be writing a series of print statements like this:
print(data[0][0])
print(data[1][0])
print(data[2][0])
I know that isn't very efficient and am hoping there is a way to use a for loop instead.
Thanks in advance for your help!
print(i[0])instead ofprint(data[0]). (The way you had it, the loop variableiwas not used, which is usually a sign that you did something wrong.)for i in data:, theiis there for a reason, right? Is it a part of the syntax, or are you allowed to change it? If you research or check your notes, you can find that you can change it, and what its purpose is. After that, it should appear suspicious that the rest of the code doesn't use it yet. That's the problem: it should be doing so. If you understand what is inieach time through the loop, then it is obvious what to do next.