3

Assume I have one variable named records that contain 3 arrays, when I tied to print

print(records)

The output is kinda like this:

records = [('foo', 'Melbourne, Australia'), ('bar', 'Jakarta, Indonesia')]
          [('john', 'Tokyo, Japan'), ('doe', 'KL, Malaysia')]
          [('foo', 'Ossining, NY'), ('doe', 'Vantaa, Findland')]

Can I merge those 3 arrays into one like this?

records = [('foo', 'Melbourne, Australia'), ('bar', 'Jakarta, Indonesia'), 
          ('john', 'Tokyo, Japan'), ('doe', 'KL, Malaysia'), 
          ('chips', 'Ossining, NY'), ('cookies', 'Vantaa, Findland')]
Algo Rithm
  • 96
  • 6
  • So, do you want to say that when you `print(records)` you get output as `[('foo', 'Melbourne, Australia'), ('bar', 'Jakarta, Indonesia')] [('john', 'Tokyo, Japan'), ('doe', 'KL, Malaysia')] [('foo', 'Ossining, NY'), ('doe', 'Vantaa, Findland')]` – CoolCoder Apr 29 '21 at 05:20
  • @CoolCoder yes, actually it looks like this https://drive.google.com/file/d/1S5DhyMzvXGOEGpk0o-Sii0zALzZ9XcXs/view – Algo Rithm Apr 29 '21 at 05:30
  • Same question [here](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) – bottombracket Apr 29 '21 at 05:37

3 Answers3

0

Your provided output list is incorrect it should be like this

x = [[('x'),('y')],[('x'),('y')]]

For solving your problem use list comprehension and just iterate through your list.

records = [[('foo', 'Melbourne, Australia'), ('bar', 'Jakarta, Indonesia')],
          [('john', 'Tokyo, Japan'), ('doe', 'KL, Malaysia')],
          [('foo', 'Ossining, NY'), ('doe', 'Vantaa, Findland')]]

new = [tuples for ls in records for tuples in ls]

output

[('foo', 'Melbourne, Australia'), ('bar', 'Jakarta, Indonesia'), ('john', 'Tokyo, Japan'), ('doe', 'KL, Malaysia'), ('foo', 'Ossining, NY'), ('doe', 'Vantaa, Findland')]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

As @CoolCoder mentioned if you want similar kind of output then

first you should wrap all arrays in the parent array and separate them with commas

then apply the following snippet:

newArr = []
for i in records:
    for j in i:
        newArr.append(j)
print(newArr)
 
Sudarshan
  • 702
  • 6
  • 24
0

Loop through the list:

records = [[('foo', 'Melbourne, Australia'), ('bar', 'Jakarta, Indonesia')],
          [('john', 'Tokyo, Japan'), ('doe', 'KL, Malaysia')],
          [('foo', 'Ossining, NY'), ('doe', 'Vantaa, Findland')]]
out = []
for rec in records:
    for r in rec:
        out.append(r)
print(out)
>>>[('foo', 'Melbourne, Australia'), ('bar', 'Jakarta, Indonesia'),
('john', 'Tokyo, Japan'), ('doe', 'KL, Malaysia'), 
('foo', 'Ossining, NY'), ('doe', 'Vantaa, Findland')]
Sid
  • 2,174
  • 1
  • 13
  • 29