Reputation: 8513
I have a list of websites in a string and I was doing a for loop to add "http" in the front if the first index is not "h" but when I return it, the list did not change.
n is my list of websites h is "http"
for p in n:
if p[0]!="h":
p= h+ p
else:
continue
return n
when i return the list, it returns my original list and with no appending of the "http". Can somebody help me?
Upvotes: 8
Views: 15876
Reputation: 123791
>>> n=["abcd","http","xyz"]
>>> n=[x[:1]=='h' and x or 'http'+x for x in n]
>>> n
['httpabcd', 'http', 'httpxyz']
Upvotes: 0
Reputation: 798536
n = [{True: '', False: 'http'}[p.startswith('h')] + p for p in n]
Don't really do this. Although it does work.
Upvotes: 0
Reputation: 38603
This could also be done using list comprehension:
n = [i if i.startswith('h') else 'http' + i for i in n]
Upvotes: 15
Reputation: 881567
You need to reassign the list item -- strings are immutable, so +=
is making a new string, not mutating the old one. I.e.:
for i, p in enumerate(n):
if not p.startswith('h'):
n[i] = 'http' + p
Upvotes: 3