FAQ: String Methods - Splitting Strings II

I think the biggest difference is that print does not return the actual variable values. Your author_last_names variable would contain the None object instead of actual author names.

Is it the same output? Double check. What about those with three provided names?

1 Like

Heh, it was that simple. Next time I’ll double check this… Thanks for helping me this fast and efficiently!

Hi I have a quick question,

uthor_names = authors.split(',')
print(author_names)
print(type(author_names))

def remove_last_name():
  authors_split = []
  for i in author_names:
    #authors_split.append(i.split())
    bob = i.split()
    authors_split.extend(bob)

  print(len(authors_split))
  authors_last_names = [authors_split[i] for i in range(len(authors_split)) if i % 2 != 0]
  print(authors_last_names)
  return authors_last_names
  #for lastname in author_names

author_last_names = remove_last_name()

In my list comprehension:

authors_last_names = [authors_split[i] for i in range(len(authors_split) - 1) if i % 2 != 0]

Returns all last names except the final name on the list.

authors_last_names = [authors_split[i] for i in range(len(authors_split)) if i % 2 != 0]

Returns all including the last name. I’m confused because I thought the due to list indexes starting at 0 meant that you had to subtract one from the length for it to work.

this:

[1, 2, 3][-1]

means we get the last value from the list (using negative indexes)

doing -1 from range, you will just not give you the last element of the list

We use split() method to split a string into a list, can we use the same method to split a list?

In this case we can know that we cannot use split() function with a list.

However, what happened when we want to separate the element within a list?

We use split_name = name.split() to split the long list into 2 element list with the first and last name at the one list. Should we consider that we split the name (an element of the author_names list), or (a list within the author_names list)? Why we can split the name but not author_names?

Because the author name is a str type object, and has a split() method. Splitting gives us a list from a string; joining gives us a str from a list.

1 Like

Thank you so much for replying!
So is that mean an element in a list is not necessary a list type? An element in a list can have any type?

1 Like

Precisely. We can even mix types in a list.

1 Like

Thank you! That is really helpful!

1 Like