riyansh.legend
riyansh.legend

Reputation: 127

Access specific entries in a python tuple

In a python tuple I want to acces the first entry. I can do that by writing:

example_tuple[0]

Now this first entry is an array of float. From this array I want to get all entries except the last one. Like descibed here, I did this by writing:

example_array[:-1]

Now I want to stack these two features and I tried it with the following command:

example_tuple[0[:-1]]

This is producing the following error:

TypeError: 'int' object is not subscriptable

I'm not sure what's wrong as there is no integer involved in this.

Upvotes: 1

Views: 61

Answers (1)

undebutant
undebutant

Reputation: 61

By typing:

example_tuple[0[:-1]]

Python tries to compute what's inside the bracket first, that is 0[:-1]. That explains the error:

TypeError: 'int' object is not subscriptable

You are trying to access 0 as an array.

As @ShubhamShaswat said, to access an array within an array, you need to get the first one, and access the value you want in it:

example_tuple = [[5.7, 2.9, 7.9], [0.1, 4.2], [1.2]]

### Using 2 steps ###
# temp_var equals [5.7, 2.9, 7.9]
temp_var = example_tuple[0]
# output: [5.7, 2.9]
print(temp_var[:-1])

### Which can be shortened in Python by assembling array access ###
# output: [5.7, 2.9]
print(example_tuple[0][:-1])

Upvotes: 2

Related Questions