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?
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?
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,