0

I have a list of integer lists. I am trying to convert it to a list of integers.

int_list = [[0], [1], [2], [3], [4], [5], [6]]

new_list = []
for i in int_list:
    new_list.append(i)

print(new_list)

Wanted output:

[0, 1, 2, 3, 4, 5, 6]

My output:

[[0], [1], [2], [3], [4], [5], [6]]
ruohola
  • 19,113
  • 6
  • 51
  • 82
ladybug
  • 119
  • 6

4 Answers4

2

A very pythonic way of doing this would be to use list comprehension:

int_list = [[0], [1], [2], [3], [4], [5], [6]]    

new_list = [value for sub_list in int_list for value in sub_list]
print(new_list)

An explaination of this can be found here: https://spapas.github.io/2016/04/27/python-nested-list-comprehensions/

There are many more ways that some people would prefer, for example a programmer who uses functional programming may prefer:

from operator import add
from functools import reduce

int_list = [[0], [1], [2], [3], [4], [5], [6]]    
print(reduce(add, int_list))

If you want a more verbose and easier to understand version, you could use:

int_list = [[0], [1], [2], [3], [4], [5], [6]]

new_list = []
for i in int_list:
    new_list.extend(i)

print(new_list)
Oli
  • 2,270
  • 1
  • 9
  • 23
1

You almost had it:

int_list = [[0], [1], [2], [3], [4], [5], [6]]    

new_list = []
for i in int_list:
    new_list.append(i[0])

print(new_list)

Output:

[0, 1, 2, 3, 4, 5, 6]
ruohola
  • 19,113
  • 6
  • 51
  • 82
1
int_list = [[0], [1], [2], [3], [4], [5], [6]]

new_list = []
for i in int_list:
    new_list += i  

print(new_list)
ComplicatedPhenomenon
  • 3,863
  • 2
  • 14
  • 39
1

1) you can use itemgetter with map

from operator import itemgetter


new_list = list(map(itemgetter(0), int_list))

print(new_list)

output:

[0, 1, 2, 3, 4, 5, 6]

2) or you can use chain from itertools

from itertools import chain

new_list = list(chain(*int_list))

print(new_list)

output:

[0, 1, 2, 3, 4, 5, 6]
kederrac
  • 15,932
  • 5
  • 29
  • 52