Jack Herer Jack Herer - 27 days ago 6
Python Question

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

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

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




Here is the problem...

I am using two
for
loops to append the same list.

The first
for
loop:

for friend in individual_friends:
friends.append(friend.text)


Which gives me:

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


the second
for
loop:

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


Which gives me:

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


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

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:
    friends.append(friend.text)

# 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"))