1

I have a got a list of Post Codes that I would like to return just the first part of it.

postcodes = list(df['postcode'][0:10])

['EC4V 3EJ', 'SE1 9DW', 'W12 7EY', 'E14 9GA', 'E17 8ES', 'N10 3LR', 'W2 2RH', 'W3 7ST', 'W2 1PW', 'W4 5RG']

for p in postcodes:
    postcodes.append(p.split()[0])
postcodes

I was expecting to get something like:

['EC4V', 'SE1', 'W12', 'E14' ...]

but my kernel keeps looping and it doesn't return anything.

AdamGold
  • 4,941
  • 4
  • 29
  • 47
  • Do not add to same list while iterating over. Change to something like `new_postcodes.append(p.split()[0])`. – Austin Jun 01 '19 at 09:11
  • Possible duplicate of [How to modify list entries during for loop?](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop) – zvone Jun 01 '19 at 09:16

2 Answers2

2

You're looping over a list and appending to it in every iteration. Your loop will never stop (each member you loop over, you add another element to the list). You should use a list comprehension for your desired output:

In [1]: l = ['EC4V 3EJ', 'SE1 9DW', 'W12 7EY', 'E14 9GA', 'E17 8ES', 'N10 3LR', 'W2 2RH', 'W3 7ST', 'W2 1PW', 'W4 5RG
   ...: ']

In [2]: [p.split()[0] for p in l]
Out[2]: ['EC4V', 'SE1', 'W12', 'E14', 'E17', 'N10', 'W2', 'W3', 'W2', 'W4']
AdamGold
  • 4,941
  • 4
  • 29
  • 47
1

Your issue is that you're appending to postcodes while looping through postcodes. So you're never able to loop through everything in postcodes as you keep adding to it each loop. Instead, you can create a new empty list such as modified_postcodes which you can append each modified postcode to:

modified_postcodes = []
for p in postcodes:
    modified_postcodes.append(p.split()[0])

print(modified_postcodes)

Alternatively, you could use pythons map method to map each postcode in postcodes to its first segment by using .split():

postcodes = ['EC4V 3EJ', 'SE1 9DW', 'W12 7EY', 'E14 9GA', 'E17 8ES', 'N10 3LR', 'W2 2RH', 'W3 7ST', 'W2 1PW', 'W4 5RG']
res = list(map(lambda p : p.split()[0], postcodes))
print(res)
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64