meme
meme

Reputation: 33

python3.2)append two element in a list(lists in a list)

If I have an input like this (1, 2, 3, 4, 5, 6) The output has to be ... [[1, 2], [3, 4], [5, 6]].

I know how to deal with if it's one element but not two.

x=[]
for number in numbers:
    x.append([number])

I'll appreciate your any help!

Upvotes: 1

Views: 175

Answers (5)

anati
anati

Reputation: 274

Very Clear solution:

l = (1, 2, 3, 4, 5, 6)
l = iter(l)
w = []
for i in l:
    sub = []
    sub.append(i)    
    sub.append(next(l))
    w.append(sub)    
print w

Upvotes: 0

Steven Summers
Steven Summers

Reputation: 5384

You can use something like this. This solution also works for list of odd length

def func(lst):
    res = []
    # Go through every 2nd value | 0, 2, 4, ...
    for i in range(0, len(lst), 2):
        # Append a slice of the list, + 2 to include the next value
        res.append(lst[i : i + 2])

    return res

# Output
>>> lst = [1, 2, 3, 4, 5, 6]
>>> func(lst)
[[1, 2], [3, 4], [5, 6]]
>>> lst2 = [1, 2, 3, 4, 5, 6, 7]
>>> func(lst2)
[[1, 2], [3, 4], [5, 6], [7]]

List comprehension solution

def func(lst):
    return [lst[i:i+2] for i in range(0, len(lst), 2)]

Slicing is better in this case as you don't have to account for IndexError allowing it to work for odd length as well.

If you want you can also add another parameter to let you specify the desired number of inner elements.

def func(lst, size = 2): # default of 2 it none specified
    return [lst[i:i+size] for i in range(0, len(lst), size)]

Upvotes: 1

Mark Hannel
Mark Hannel

Reputation: 795

There's a few hurdles in this problem. You want to iterate through the list without going past the end of the list and you need to deal with the case that list has an odd length. Here's one solution that works:

def foo(lst):
    result = [[x,y] for [x,y] in zip(lst[0::2], lst[1::2])]
    return result

In case this seems convoluted, let's break the code down.

  • Index slicing: lst[0::2] iterates through lst by starting at the 0th element and proceeds in increments of 2. Similarly lst[1::2] iterates through starting at the 1st element (colloquially the second element) and continues in increments of 2. Example:

    >>> lst = (1,2,3,4,5,6,7)
    >>> print(lst[0::2])
    (1,3,5,7)
    >>> print(lst[1::2])
    (2,4,6)
    
  • zip: zip() takes two lists (or any iterable object for that matter) and returns a list containing tuples. Example:

    >>> lst1 = (10,20,30, 40)
    >>> lst2 = (15,25,35)
    >>> prit(zip(lst1, lst2))
    [(10,15), (20,25), (30,35)]
    

    Notice that zip(lst1, lst2) has the nice property that if one of it's arguments is longer than the other, zip() stops zipping whenever the shortest iterable is out of items.

  • List comprehension: python allows iteration quite generally. Consider the statement:

    >>> [[x,y] for [x,y] in zip(lst1,lst2)]
    

    The interior bit "for [x,y] in zip(lst1,lst2)" says "iterate through all pairs of values in zip, and give their values to x and y". In the rest of the statement "[[x,y] for [x,y] ...]", it says "for each set of values x and y takes on, make a list [x,y] to be stored in a larger list". Once this statement executes, you have a list of lists, where the interior lists are all possible pairs for zip(lst1,lst2)

Upvotes: 0

Nurjan
Nurjan

Reputation: 6053

There is a shorter way of doing what you want:

result = []
L = (1,2,3,4,5,6,7,8,9,10)
result = [[L[i], L[i + 1]] for i in range(0, len(L) - 1, 2)]
print(result)

Upvotes: 1

Jake Conway
Jake Conway

Reputation: 909

Something like this would work:

out = []
lst = (1,2,3,4,5,6,7,8,9,10)
for x in range(len(lst)):
    if x % 2 == 0:
        out.append([lst[x], lst[x+1]])
    else:
        continue

To use this, just set lst equal to whatever list of numbers you want. The final product is stored in out.

Upvotes: 1

Related Questions