Python: Why do these lines of code display different values?

jackcrouch :

I am relatively new to coding and python and I am trying to wrap my head round some concepts. One I am struggling on is the split() function and why these two pieces of code produce two different outputs

y = ["hello\n", "world\n", "python\n"]
x = [line.strip() for line in y]
print(x)

and

y = ["hello\n", "world\n", "python\n"]
for line in y:
    x = [line.strip()]
print(x)

The first piece of code produces an output of

['hello', 'world', 'python']

Whilst the second produces

['python']

Does anyone know why this is, as to me they should do the same thing by both producing an output of

['python']

thanks

abhiarora :

Does anyone know why this is, as to me they should do the same thing by both producing an output of ['python'].

Your first code uses list comprehension which is used to create a sequence. It provides a concise way to create lists or sequence of elements.

Your second code is basically using a for loop just to get the last element of list y. for loop is used if you want to iterate through a sequence. However, you are also overwriting the variable x in each of your iteration and hence, when you come out of for loop, it will be pointing to the last element (i.e., ['python']). Try this:

for line in y:
    x = [line.strip()]
    print(x)

If you just want the last element of your list y and strip() it, you can also do that via:

x = [ y[-1].strip() ]

OR

If you want the list, then use your first code.

MORE INFORMATION

If you can change your second code to:

x = [ ]
y = ["hello\n", "world\n", "python\n"]
for line in y:
    x.append(line.strip())
print(x)

Then both will print same output (i.e., ['hello', 'world', 'python']).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386750&siteId=1