Search code examples
pythonlistjupyter-notebookappendfor-in-loop

Python: List Index Out of Range / Append List


Here is my list sample (data): Address list Here is the snippet of the list:

['PO Box 4653, Stockton, California, 95204',
 '157 Adams St., Stockton, California, 95204', ...

Here is my problem: List index out of range (1) 'int' object is not iterable (2)

Please note that solutions like for i in a_list: and for i in range(len(a_list): generates 'Error: list index out of range'

Explanation: My Address list has no nulls and I tried appending empty 'city_list' in a variety of ways as seen on the images... nothing seems to work. I am not sure how can I append my empty list - please help!

Goal: Grab 'a_list' and split each string in a for-in-loop, grab city value (index 1) and append it to an empty list 'city_list'


Solution

  • This should work:

    a_list = ['PO Box 4653, Stockton, California, 95204','157 Adams St., Stockton, California']
    
    city_list = []
    for i in range(0,len(a_list)):
        city_name = a_list[i].split(",")[1].strip()
        city_list.append(city_name)
    
    print(city_list)