Home > Back-end >  what does this line of code mean - elif left[0] > right[0]:?
what does this line of code mean - elif left[0] > right[0]:?

Time:11-28

I'm new to python and would appreciate any help i can

I'm looking at this code :

  if left[0] < right[0]:
            result.append(left[0])
            left = left[1:]
        elif left[0] > right[0]:
            result.append(right[0])
            right = right[1:]
        max_iter -= 1

it doesn't make sense what it means , its about changing the order of numbers in a sequence to ascending order but what does [0] mean?

CodePudding user response:

If you have a list, like s = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'], then you can print out print(s[0]), which will output H, as it is the first element in the list (Remember, programming languages start counting at 0, so [0] means the first element).

Further, you can print out multiple elements of a list by using print(s[1:6]) which will print out ['e', 'l', 'l', 'o', ' '], as these are the second two seventh elements.

You can also use print(s[1:]) which will print from the second element to the end (['e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']) or print(s[:6]) to print from the start to the seventh character (['H', 'e', 'l', 'l', 'o', ' '])

Hope this helps and that I understood your question right.

CodePudding user response:

[0] means the element at 0 index. Index always starts from 0. In iterable datatypes, index represents the position of the element. For example, if we have a list say l=[1,2,3,4,5]. Here, 1,2,3,4,5 are elements but the positions i.e. the index starts from zero. So the index value of 1 is 0, index of 2 is 1 index of 3 is 2 and so on. If we have another example say x=["hi","go","come","speak"], then the index value of "hi" is 0, index of "go" is 1, index of "come" is 2 and index of "speak" is 3. Now, to acces the 3rd element (which is at 2nd index) we use <variable>[<index>] . Here, to acces the 3rd element i.e. "come", we use x[2]

  • Related