Can negative indexing be used with lists?

0105

Yes, negative indexing can be used with lists in Python, just like with strings. It allows you to access elements from the end of the list.

Example:

For a list my_list = [10, 20, 30, 40, 50]:

  • my_list[0] gives 10 (first element)
  • my_list[1] gives 20 (second element)
  • my_list[-1] gives 50 (last element)
  • my_list[-2] gives 40 (second last element)

Benefits:

  • Convenience: Easily access the last elements without needing to calculate the length of the list.
  • Flexibility: Works the same way for any list size.

If you have more questions or need further examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!