简体   繁体   中英

Is there a difference between these two expressions in python

So, basically I just started learning python and I can't find something that proves if these two instructions do the same thing or not I have two lists and I want to copy one into another, the thing is that I do not understood if this instruction is right
newList = [x[:] for x in List] because newList = List does the same thing Is there a difference between these two instructions? Thanks!

In the first cursory look they look essentially same but there could be a difference if the List is not a list of lists [as is immediately understood by its name] ..if List is actually a tuple of tuples (supposing a naming mistake .. :-)) or something else. In such a case you are creating a list of tuples (by the first command) from what was initially something else. Other such possibilities also exist. So please see the print and type of NewList and List carefully. A subtle difference and they are not same.

You might be actually doing a type conversion if you are following the first command.

Consider the code below.

List = tuple( (x,x+1) for x in range(10))
newList = [x[:] for x in List]

The output of print and type reveal the difference instantly.

print(List)
print(newList)
type(List)
type(newList)

respective Outputs

((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
<class 'tuple'>
<class 'list'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM