-2

example: [1233456]

How to access the fourth element? Basically I am taking input from the user, but when I print the length it shows me one and if I put a comma in between the numbers it shows correctly. So I want to access an element from a number as I ask before.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

0
int(str(ex[0])[3])

The program takes the 1st element of the list(which in your case is '1233456'), converts it into a string(because integers are not subscriptable). Takes the fourth character of the string, which has an index of 3 as indexes in python start at 0. And finally, converts it back to an integer.

kailashT
  • 1
  • 2
0

I think this resource on Sequential Data Types might help you.

When you have [1233456] it's actually one single integer as the first element (0) in a list.

If you cast it to a string, you can pick out the individual characters, which you can then cast back to integers with int():

>>> my_ints = [1233456]
>>> my_str = str(my_ints[0])
>>> my_str[2]
'3'
>>> int(my_str[2])
3

Please remember [2] is the third element of the list, as they are zero-indexed... ;-)

Hope that helps!!!

JimCircadian
  • 171
  • 7
  • if i typcast my list to the integer from string it shows me error ex_ d = int(str(my_lst)) – chinmay_567 Jul 10 '20 at 15:03
  • Hello Chinmay. Please note you can't cast the list to a string. In the example I cast the first element of the list (the integer 1233456) to a string: `str(my_ints[0])`. If you need some help with lists and how they work I would definitely review that link I mentioned!!! :-) – JimCircadian Jul 10 '20 at 15:23