Splitting String in Python

author_last_names =
for name in author_names:
author_last_names.append(name.split()[-1])

print(author_last_names)

I couldn’t understand this code… please someone explain this FOR loop ? what it does and how?

The for loop is designed to iterate over all members of an iterable, from left to right.

for  iterator_variable  in  iterable:

for => loop keyword
variable => is assigned a value in turn
in => membership keyword
iterable => str, list, tuple, dict, set, or iterator object

Is it the code inside the loop that raising this question?

1 Like

The for loop here iterates through all elements in author_names, from the smallest index to the largest index, which is from left to right in the array.
The syntax of a for loop is:

for val in sequence:

val accesses each item of sequence on each iteration. Loop continues until we reach the last item in the sequence.
In your provided code, the for loop iterators through every element in author_names. Then for each element (which is name), it separates name by spaces and whitespaces (which is name.split()). After that, it assigns the last separated value (which is [-1] from name into author_last_names (which is .append).

^ Working of Python for loop from Python for Loop (With Examples)

Here’s an explain with your code,

author_names = ["a", "b", "c"]; #Here we declare an array with 3 elements. author_last_names = []; #Here's an empty array to hold new elements. for name in author_names: author_last_names.append(name.split()[-1]); #So here, there exist 3 elements in author_names. The for loop will then loop for 3 times by iterating through every element in author_names. Below is what happens in the for loop; #BEFORE the first loop, it checks the terminating loop condition, which is when it iterates past the last element in author_names. It still hasn't passed through it. #First Loop: #author_last_names = ["a"]; #BEFORE the second loop, it checks the terminating loop condition, which is when it iterates past the last element in author_names. It still hasn't passed through it. #Second Loop: #author_last_names = ["a", "b"]; #BEFORE the third loop, it checks the terminating loop condition, which is when it iterates past the last element in author_names. It still hasn't passed through it. #Third Loop: #author_last_names = ["a", "b", "c"]; #BEFORE the fourth loop, it checks the terminating loop condition, which is when it iterates past the last element in author_names. Then it breaks out from the loop. print(author_last_names);

https://wiki.python.org/moin/ForLoop

2 Likes