-1

How do I unnest a nested list or flatten a nested list.

so that,

servers  = [["10.10.10.10" , "20.20.20.20"] ,["30.30.30.30"] , ["40.40.40.40", "50.50.50.50"] , ["60.60.60.60"],["70.70.70.70"]]

becomes,

servers  = ["10.10.10.10" , "20.20.20.20"] ,["30.30.30.30"] , ["40.40.40.40", "50.50.50.50"] , ["60.60.60.60"],["70.70.70.70"]

All help welcome thanks

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
degixer
  • 39
  • 10
  • would [`servers = list(chain(*servers))`](https://docs.python.org/3/library/itertools.html#itertools.chain) suffice? – Felk Sep 27 '17 at 11:59

2 Answers2

2

But what type of data do you expect? By defining

x = item1, item2

You get a tuple. You can convert list to tuple by

servers = tuple(servers)

That gives you:

 (["10.10.10.10" , "20.20.20.20"] ,["30.30.30.30"] , ["40.40.40.40", "50.50.50.50"] , ["60.60.60.60"],["70.70.70.70"])

Or you can flatten you list:

servers = [el for item in servers for el in item]

But then you will get:

["10.10.10.10" , "20.20.20.20" ,"30.30.30.30" , "40.40.40.40", "50.50.50.50" , "60.60.60.60","70.70.70.70"]
Widelec
  • 31
  • 2
  • I just needed to "loose" the outer brackets so I could zip the list to another list. I never realized I could use the tuple command. completely flattening the list is not in scope for what i'm trying to achieve as I intend to use the zip function later on. – degixer Sep 27 '17 at 12:12
0

you simply cannot have that way. when you say

a = 1, 2, 3
print(a)

it outputs

(1, 2, 3)

so you can either has a tuple or a list but not without () or []

Gajendra D Ambi
  • 3,832
  • 26
  • 30