Home > OS >  Python: Appending a list by other lists
Python: Appending a list by other lists

Time:11-26

I want to append the lists "b", "c" and "d" to my list "a". Then i want to print the single lists in each line. My expected output is:

[(4, 'Blue'), (3, 'Red'), (4, 'Red')]
[(2, 'Green'), (4, 'Green'), (1, 'Yellow')]
[(1, 'Green'), (3, 'Blue'), (3, 'Green')]
[(2, 'Blue'), (1, 'Red'), (4, 'Yellow')]

My current code is:

a = [(4, 'Blue'), (3, 'Red'), (4, 'Red')]
b = [(2, 'Green'), (4, 'Green'), (1, 'Yellow')]
c = [(1, 'Green'), (3, 'Blue'), (3, 'Green')]
d = [(2, 'Blue'), (1, 'Red'), (4, 'Yellow')]

a.append(b)
a.append(c)
a.append(d)

for x in a:
    print(x)

My current output is:

(4, 'Blue')
(3, 'Red')
(4, 'Red')
[(2, 'Green'), (4, 'Green'), (1, 'Yellow')]
[(1, 'Green'), (3, 'Blue'), (3, 'Green')]
[(2, 'Blue'), (1, 'Red'), (4, 'Yellow')]

As you see the first 3 lines of output are separated and not together. How can I change this so that it appears according to my expected output?

CodePudding user response:

Your current code adds each b/c/d list as an element. So you have a list with 6 element, the last 3 of which are lists.

[(4, 'Blue'),
 (3, 'Red'),
 (4, 'Red'),
 [(2, 'Green'), (4, 'Green'), (1, 'Yellow')],
 [(1, 'Green'), (3, 'Blue'), (3, 'Green')],
 [(2, 'Blue'), (1, 'Red'), (4, 'Yellow')]]

I think what you want to do is use a larger container. (WHY? I don't know, I guess it's a dummy example part of a larger code).

a = [(4, 'Blue'), (3, 'Red'), (4, 'Red')]
b = [(2, 'Green'), (4, 'Green'), (1, 'Yellow')]
c = [(1, 'Green'), (3, 'Blue'), (3, 'Green')]
d = [(2, 'Blue'), (1, 'Red'), (4, 'Yellow')]

out = [a]
out.append(b)
out.append(c)
out.append(d)
# or out = [a,b,c,d]
# or out.extend([b,c,d])

for x in out:
    print(x)

output:

[(4, 'Blue'), (3, 'Red'), (4, 'Red')]
[(2, 'Green'), (4, 'Green'), (1, 'Yellow')]
[(1, 'Green'), (3, 'Blue'), (3, 'Green')]
[(2, 'Blue'), (1, 'Red'), (4, 'Yellow')]

CodePudding user response:

The problem here is that you are appending b, c, and d as elements to a, which means that the original elements of a are not nested in a list like that of b, c, and d.

To package the elements of a into a list first, we can do a = [a] before the appending.

So our code now becomes:

a = [(4, 'Blue'), (3, 'Red'), (4, 'Red')]
b = [(2, 'Green'), (4, 'Green'), (1, 'Yellow')]
c = [(1, 'Green'), (3, 'Blue'), (3, 'Green')]
d = [(2, 'Blue'), (1, 'Red'), (4, 'Yellow')]

a = [a]
a.append(b)
a.append(c)
a.append(d)

for x in a:
    print(x)

Output:

(4, 'Blue'), (3, 'Red'), (4, 'Red')]
[(2, 'Green'), (4, 'Green'), (1, 'Yellow')]
[(1, 'Green'), (3, 'Blue'), (3, 'Green')]
[(2, 'Blue'), (1, 'Red'), (4, 'Yellow')]

CodePudding user response:

My expected output should be:

[(4, 'Blue'), (3, 'Red'), (4, 'Red')]
[(2, 'Green'), (4, 'Green'), (1, 'Yellow')]
[(1, 'Green'), (3, 'Blue'), (3, 'Green')]
[(2, 'Blue'), (1, 'Red'), (4, 'Yellow')]

That's not a valid list. It's just four different lists.

  • Related