Krexxen
Krexxen

Reputation: 23

Index Operators and lists in Python

i am currently learning Python basics in a course on our university, there is one question which i am currently not able to answer : The task is :

Change the variables on the first section, so that every if command will be solved as True, you should get a 1-3 listed if you run the code.

# Change the Code below here
number = 10
first_array = [5, 6, 7, 8] 

# If code
if number > 15:
    print("1")

if len(first_array) == 5:
    print("2")

second_array = ["one", "two", first_array]
if second_array[2][3]+3 == 10:
    print("3")

I tried to use this Code :

# Change the Code below here
number = 16
first_array = [7, 0, 0, 0, 0] 

# if code
if number > 15:
    print("1")

if len(first_array) == 5:
    print("2")

second_array = ["one", "two", first_array]
if second_array[2][3]+3 == 10:
    print("3")

Can someone explain to me how exactly second_array[2][3]+3 will be solved? I tried googling with Index Operators but couldnt find the correct answer to help me with this problem.

Upvotes: 2

Views: 180

Answers (3)

Thomas B
Thomas B

Reputation: 1

first_array[3]+3 == 10 <=> first_array[3] == 7

so with first_array = [7, 0, 0, 7, 0] , the test condition will answer True

Upvotes: 0

Dudly01
Dudly01

Reputation: 503

When you do second_array = ["one", "two", first_array] then the values of second_array become ["one", "two", [7,0,0,0,0]].

Because of this, second_array[2][3] can be read as "second_array's third element's fourth element" (cause of the 0-based indexing).

So the second_array[2][3] is the element marked by x: ["one", "two", [7,0,0,X,0]]

Upvotes: 0

Lev M.
Lev M.

Reputation: 6269

These are actually Python lists.

A list in Python can contain anything as its member, and different members can be of different types.

This line:

second_array = ["one", "two", first_array]

builds a list with 3 members: two strings, and the entire first_array as its 3rd member.

You are probably thinking that it combines two lists giving you this:

[ "one", "two", 7, 0, 0, 0, 0 ]

but that is not correct!

What you really get is:

[ "one", "two", [ 7, 0, 0, 0, 0 ] ]

A list within a list, or array inside the array.

That is why this line:

if second_array[2][3]+3 == 10:

Has two indexes, each in its own set of brackets []
The first (from the left) is for the outer list, and the second is for the inner list.

You could also write it like this:

member = second_array[2]
if member[3] + 3 == 10:

Try putting print member after the first line and see what happens.

Upvotes: 2

Related Questions