Python Tutorials

Overview

Python list items are indexed and can be accessed by referring to their index number.

Accessing Items

The following will print the second item in the list.

my_list = ["Ferrari", "Maserati", "Alfa Romeo"]
print(my_list[1]) #Maserati

Note

Arrays count starting from zero NOT one. So item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on.

Negative Indexing

Negative indexing means start from the end and count backwards when accessing items.

  • -1 refers to the last item
  • -2 refers to the second last item
  • etc.
my_list = ["Ferrari", "Maserati", "Alfa Romeo"]
print(my_list[-1]) #Alfa Romeo

Range of Indexes

A range of indexes can be included by specifying where to start and where to end the range.

When specifying a range, the returned value will be a new list with the specified items.

my_list = ["Lamborghini", "Ferrari", "Maserati", "Alfa Romeo", "Porsche"]
print(my_list[1:3]) #['Ferrari', 'Maserati']

By leaving out the start value, the range will start at the first item.

my_list = ["Lamborghini", "Ferrari", "Maserati", "Alfa Romeo", "Porsche"]
print(my_list[:3]) #['Lamborghini', 'Ferrari', 'Maserati']

Note

The last number in a range is NOT INCLUSIVE!

Range of Negative Indexes

Specify negative indexes to start the range search from the end of the list.

my_list = ["Lamborghini", "Ferrari", "Maserati", "Alfa Romeo", "Porsche"]
print(my_list[-3:-1]) #['Maserati', 'Alfa Romeo']

Check if an Item Exists

To determine if a specified item is present in a list use the “in” keyword.

my_list = ["Ferrari", "Maserati", "Alfa Romeo"]

if "Maserati" in my_list:
    print("'Maserati' is in the list")

Output:

'Maserati' is in the list

Python Notes:

  • The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
  • Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
  • Python string methods return new values, and DO NOT change the original string

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.