11

i have list with lists of strings looks like

allyears
#[['1916'], ['1919'], ['1922'], ['1912'], ['1924'], ['1920']]

i need to have output like this:

#[1916, 1919, 1922, 1912, 1924, 1920]

have been try this:

for i in range(0, len(allyears)): 
    allyears[i] = int(allyears[i]) 

but i have error

>>> TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Georgy
  • 12,464
  • 7
  • 65
  • 73
germanjke
  • 529
  • 1
  • 5
  • 13

6 Answers6

9

You can simply do this:

allyears = [int(i[0]) for i in allyears]

Because all the elements in your allyears is a list which has ony one element, so I get it by i[0]

The error is because ypu can't convert a list to an int

Binh
  • 1,143
  • 6
  • 8
6

You're very close, you just need to take the first (and only) element of allyears[i] before doing the int conversion:

for i in range(0, len(allyears)): 
    allyears[i] = int(allyears[i][0]) 

Alternatively, you could do this in one line using a list comprehension:

allyears = [int(l[0]) for l in allyears]
dspencer
  • 4,297
  • 4
  • 22
  • 43
5

if you want a simple for loop you also may use enumerate built-in function and unpack your inner list:

for i, [n] in  enumerate(allyears): 
    allyears[i] = int(n) 

you can use a list comprehension:

allyears = [int(e) for l in allyears for e in l]

also, you can use itertools.chain

from itertools import chain

list(map(int, chain.from_iterable(allyears)))

output:

[1916, 1919, 1922, 1912, 1924, 1920]

the last 2 solutions will work also if in your inner lists you have more than one element

kederrac
  • 16,819
  • 6
  • 32
  • 55
2

You need to access individual elements of the list instead of lists itself.

Try:

for i in range(0, len(allyears)): 
    allyears[i] = int(allyears[i][0]) 
Hamza Khurshid
  • 765
  • 7
  • 18
1

Try:

allyears = [['1916'], ['1919'], ['1922'], ['1912'], ['1924'], ['1920']]

out = []
for i in range(0, len(allyears)): 
    out.append(int(allyears[i][0]))

print (out)
m8factorial
  • 188
  • 6
0

You tried this:

for i in range(0, len(allyears)): 
    allyears[i] = int(allyears[i]) 

and got the error

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

The next thing you should have tried is:

for i in range(0, len(allyears)): 
    print(allyears[i])

And you would have seen that you are looping through these values:

['1916']
['1919']
['1922']

etc.

Those cannot be converted to int using int(), because those are lists. You should get the only element of those lists using the [0] index like this:

>>> for i in range(0, len(allyears)): 
...    print(allyears[i][0])
1916
1919
1922...

And now you know how to correct your original code:

for i in range(0, len(allyears)): 
    allyears[i] = int(allyears[i][0])

The more Pythonic solution to your problem would use list comprehension:

allyears = [int(i[0]) for i in allyears]
theonlygusti
  • 11,032
  • 11
  • 64
  • 119