Jack Herer Jack Herer - 9 months ago 58
Python Question

Python 3 | Appending a string to an item in a list?

After trying many different methods for this problem, such as nested

loops (which iterate over the first list as many times as the length of the second iteration), and I've tried
which I couldn't get to do what I wanted.

Here is the problem...

I am using two
loops to append the same list.

The first

for friend in individual_friends:

Which gives me:

['Jody Ann Elizabeth Lill\n98 mutual friends\nFriends',
'Jayde Woods\n56 mutual friends\n4 new posts\nFriends']

the second

for link in individual_friends_links:
links = link.get_attribute("href")

Which gives me:

['Jody Ann Elizabeth Lill\n98 mutual friends\nFriends',
..., '
Jayde Woods\n56 mutual friends\n4 new posts\nFriends',

What I actually want is:

['Jody Ann Elizabeth Lill\n98 mutual friends\nFriends\nhttps://m.facebook.com/jodyannelizabeth.lill?ref=bookmarks',
'Jayde Woods\n56 mutual friends\n4 new posts\nFriends\nhttps://m.facebook.com/jayde.woods?ref=bookmarks']

Answer Source

The Error

The mistake you are making is that, by calling append, you are always adding to the end of friends.

But for your links, you don't want to add to the end of friends, you want to change the value of an element already in friends.

The Solution

You need something more like this:

# create your list of friends
for friend in individual_friends:

# for every *i*th link, look up the *i*th friend in `friends`,
# and modify that value, instead of adding to the end of `friends`.
for link_index, link in enumerate(individual_friend_links):
    friends[link_index] = friends[link_index] + '\n' + link.get_attribute("href")

The Better Solution

But this is verbose. There is no need to do two explicit for-loops. You need the power of zip, which will merge your two separate lists into a single list of 2-tuples and do exactly the same as the above.

for friend, link in zip(individual_friends, individual_friends_links):
    friends.append(friend.text + '\n' + link.get_attribute("href"))