-1

I have this variable of type long that is a list of longs:

print(list_id)
[6L]
[6L]
[6L]
[6L]
[7L]

How to convert this list to something like:

list_id = [6, 6, 6, 6, 7]

I did something like this:

list_orgs_id = []
for i in list_id[0]:
    list_orgs_id.append(i)
print(list_orgs_id)

but it says:

TypeError: 'long' object is not iterable
Souad
  • 4,856
  • 15
  • 80
  • 140

3 Answers3

1

You can cast them to integers with int().

list_id = [[6L], [6L], [6L], [6L], [7L]]
int_id = [int(i[0]) for i in list_id]
print(int_id)

Output:

[6, 6, 6, 6, 7]

Terminal output:

Python 2.7.10 (default, Oct  6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> list_id = [[6L], [6L], [6L], [6L], [7L]]
>>> int_id = [int(i[0]) for i in list_id]
>>> print(int_id)
[6, 6, 6, 6, 7]
>>>
Jim Wright
  • 5,905
  • 1
  • 15
  • 34
1

Do you want something like this?Simply use list comprehension

main_list = [[1,2,3],[2,3,4]]
list_id=[j for i in main_list for j in i]
print(list_id)

Output:

[1, 2, 3, 2, 3, 4]
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
0

Method 1

You could apply int() to all the elements in the list of list:

for x in range(len(list_id)):
    list_id[x] = int(list_id[x][0])

Method 2

You could also choose to write it in a fancy list comprehension:

list_id = [int(y) for x in list_id for y in x]

In this case you have to iterate over all the lists inside list_id and during each iteration you will iterate over the long integer inside those list. This is similar to:

temp = []

for x in list_id:
    for y in x:
        temp.append(int(x))

list_id = temp

Method 3

You could, if you want, write a user defined function and apply that using map() function on all the elements of list_id:

def func(list):
    return int(list[0])

list_id = map(func, list_id)

list_id = list(map)
# This line is not required if you just want to iterate over the values.
Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33