views:

128

answers:

4

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?

+2  A: 

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
Alex Martelli
+5  A: 

This could also be done using list comprehension:

n = [i if i.startswith('h') else 'http' + i for i in n]
Max Shawabkeh
A: 
n = [{True: '', False: 'http'}[p.startswith('h')] + p for p in n]

Don't really do this. Although it does work.

Ignacio Vazquez-Abrams
Then why do you suggest it?
Arrieta
Probably because it's an amusingly hacky way of doing it.
Max Shawabkeh
Just FYI: Python has if-else expressions now, so the dict/sequence/and-or hacks to simulate them aren't necessary anymore. See Max S.'s answer for a de-hackified version of yours.
Laurence Gonsalves
@Laurence: Their "misorder" compared to the C ternary operator makes me avoid them because I don't need inexperienced Python programmers coming from other languages tripping over them. Not that it's a reason to use a dict for it though...
Ignacio Vazquez-Abrams
A: 
>>> n=["abcd","http","xyz"]

>>> n=[x[:1]=='h' and x or 'http'+x for x in n]

>>> n
['httpabcd', 'http', 'httpxyz']
S.Mark
Will fail for an empty string. But hopefully there won't be too many of those.
Ignacio Vazquez-Abrams
have you tried? :-) `[:1]` is used instead of `[0]` for that case.
S.Mark
No, I thought I saw a problem with the logic, but I was mistaken in this particular case. If the condition had been `x[:1]!='h'` then it would have failed.
Ignacio Vazquez-Abrams
Yes :-) thats how `and or` working as you know, I intentionally use `=='h'` for this case, to avoid `''` going to `and` part
S.Mark