Concatenate and Merge lists

suggest change
  1. The simplest way to concatenate list1 and list2:
    merged = list1 + list2
  2. zip returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables:
    alist = ['a1', 'a2', 'a3']
    blist = ['b1', 'b2', 'b3']
    
    for a, b in zip(alist, blist):
        print(a, b)
     
    # Output:
    # a1 b1
    # a2 b2
    # a3 b3

    If the lists have different lengths then the result will include only as many elements as the shortest one:

    alist = ['a1', 'a2', 'a3']
    blist = ['b1', 'b2', 'b3', 'b4']
    for a, b in zip(alist, blist):
        print(a, b)
    
    # Output:
    # a1 b1
    # a2 b2
    # a3 b3
    
    alist = []
    len(list(zip(alist, blist)))
    
    # Output:
    # 0
    
    For padding lists of unequal length to the longest one with `None`s use `itertools.zip_longest` (`itertools.izip_longest` in Python 2)
    
    alist = ['a1', 'a2', 'a3']
    blist = ['b1']
    clist = ['c1', 'c2', 'c3', 'c4']
    
    for a,b,c in itertools.zip_longest(alist, blist, clist):
        print(a, b, c)
    
    # Output: 
    # a1 b1 c1
    # a2 None c2
    # a3 None c3
    # None None c4
  3. Insert to a specific index values:
    alist = [123, 'xyz', 'zara', 'abc']
    alist.insert(3, [2009])
    print("Final List :", alist)

    Output:

    Final List : [123, 'xyz', 'zara', 2009, 'abc']

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


List:
* List
* Concatenate and Merge lists

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve