Appending a list to itself in Python

前端 未结 5 2304
盖世英雄少女心
盖世英雄少女心 2021-01-05 06:08

I want to attach a list to itself and I thought this would work:

x = [1,2]
y = x.extend(x)
print y

I wanted to get back [1,2,1,2]

相关标签:
5条回答
  • 2021-01-05 06:38

    or just:

    x = [1,2]
    y = x * 2
    print y
    
    0 讨论(0)
  • 2021-01-05 06:51

    x.extend(x) will extend x inplace.

    >>> print x
    
    [1, 2, 1, 2]
    
    0 讨论(0)
  • 2021-01-05 06:53

    If you want a new copy of the list try:

    x = [1,2]
    y = x + x
    print y # prints [1,2,1,2]
    

    The difference is that extend modifies the list "in place", meaning it will always return None even though the list is modified.

    0 讨论(0)
  • 2021-01-05 06:54

    x.extend(x) does not return a new copy, it modifies the list itself.

    Just print x instead.

    You can also go with x + x

    0 讨论(0)
  • 2021-01-05 07:00

    x.extend(x) modifies x in-place.

    If you want a new, different list, use y = x + x.

    0 讨论(0)
提交回复
热议问题