Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to write a for each in python3 that modifies the array?

Let’s say for example that I have an array that represents a name and I want to use just the first letter of any part of a name that is not the first or the last part:

# Have
name = ["John", "Banana", "Doe"]

# Want
["John", "B", "Doe"]

Can I iterate through a subset of an array and change the variables inside it through the variable that references it like so?

for part in name[1:-1]:
    part = part[0]

The only solution I fould for this was to use list comprehention, but it was too hard to read:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

name = [part if i in [0, len(name)-1] else part[0] for i, part in enumerate(name)]

>Solution :

v = v[0] reassigns the name v, that was previously bound to one of the list elements. This does not mutate the list, though.

You could fix your loop by iterating over an index range and explicitly reassign list elements.

for index in range(1, len(name) - 1):
    name[index] = name[index][0]

An easier to read list-comprehension solution would be:

name[1:-1] = [v[0] for v in name[1:-1]]

An equivalent solution without a list comprehension would be:

new_values = []

for v in name[1:-1]:
    new_value = v[0]
    new_values.append(new_value)

name[1:-1] = new_values

Bonus: repeating [1:-1] twice is not as clean as it could be. You could define a slice object to refer to the desired part of the list, e.g.

where = slice(1, -1)
name[where] = [v[0] for v in name[where]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading