0

I have an array that I would like to take a portion of each element of the array.

id = [000222000,000333000,000444000]

id2 = [222,333,444]

In order to be able to get id2 array I am using a for loop as follows:

id2 = [i[3:5] for i in id]

However, I get an IndexError: invalid index to a scalar variable. I don't understand why am I getting this error and how to overcome it? Also is it a same principle if I have array of strings instead of numbers?

1
  • Thank you for your help. That was just a simple example, I am converting it from another programming language and things got messy a bit. It is annoying that we can slice the string but not the integer. Commented Apr 29, 2020 at 9:14

2 Answers 2

1

The problem is that you can't slice numbers in python. If you want to slice the elements, you could cast everything to a string, slice them, then cast everything back to an integer.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help. It is annoying that we can slice the string but not the integer.
1

You are trying to slice integers, which is not possible as of right now in python 3.x

P.S

-It is not a good practice to name your list id as it is a used function in python.
-Try changing everything to Strings if you want to slice.. + change it from [3:5] to [3:6] as it does not include the last index, so you are only selecting two digits and not 3 as I suppose you want..
- It is not possible to have leading zeros in decimal base in python.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.