Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

negative index python

# Negative indexes python in lists!

# Hey everybody! Looking how to do negative indexes?
# LET'S GET INTO IT!

# Have a list first, let's say your favorite colors! 
# (Mine in this case don't know about you)

fav_color = ["Blue", "White", "Grey", "Black", "Orange", "Red", 
            "Teal", "Cyan", "Green"]

# Woah so many favorite colors! I have many but I can't add too much

"""
Anyway, let's say we wanted to print the 
last item but we don't know the last index
is. (The length is 9, and the last index is 8)

We can use negative indexes! Let's write the
print function first. Inside the parentheses,
we mention a specific fav_color index.

Like this:

print(fav_color[])

Inside the brackets, we'll add a dash (-) aka
the subtraction symbol in Mathematics. Since we
want to mention the string "Green", we'll add the
integer 1 like this:

[-1]

The full syntax below:
"""

print(fav_color[-1])

# Green probably printed out: right?

"""Now you go try this yourself, print
the "Teal" index. (the third to the last
index). Here's the answer:"""

print(fav_color[-3])
Source by www.codeproject.com #
 
PREVIOUS NEXT
Tagged: #negative #index #python
ADD COMMENT
Topic
Name
4+4 =