How to append multiple values to a list in Python

前端 未结 4 1988
醉梦人生
醉梦人生 2020-11-30 17:35

I am trying to figure out how to append multiple values to a list in Python. I know there are few methods to do so, such as manually input the values, or put the append oper

相关标签:
4条回答
  • 2020-11-30 18:11
    letter = ["a", "b", "c", "d"]
    letter.extend(["e", "f", "g", "h"])
    letter.extend(("e", "f", "g", "h"))
    print(letter)
    ... 
    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
        
    
    0 讨论(0)
  • 2020-11-30 18:15

    You can use the sequence method list.extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.

    >>> lst = [1, 2]
    >>> lst.append(3)
    >>> lst.append(4)
    >>> lst
    [1, 2, 3, 4]
    
    >>> lst.extend([5, 6, 7])
    >>> lst.extend((8, 9, 10))
    >>> lst
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    >>> lst.extend(range(11, 14))
    >>> lst
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
    

    So you can use list.append() to append a single value, and list.extend() to append multiple values.

    0 讨论(0)
  • 2020-11-30 18:17

    Other than the append function, if by "multiple values" you mean another list, you can simply concatenate them like so.

    >>> a = [1,2,3]
    >>> b = [4,5,6]
    >>> a + b
    [1, 2, 3, 4, 5, 6]
    
    0 讨论(0)
  • 2020-11-30 18:26

    If you take a look at the official docs, you'll see right below append, extend. That's what your looking for.

    There's also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.

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