Python List Tutorial: A Comprehensive Guide for Beginners
In this tutorial, we’ll cover the basics of working with lists in Python. Lists are a very common data structure in Python and are used to store collections of items.
Creating a list
To create a list in Python, you simply enclose a comma-separated sequence of items in square brackets. For example:
fruits = ["apple", "banana", "cherry"]
This creates a list called fruits
that contains three strings: "apple", "banana", and "cherry".
Accessing list items
You can access individual items in a list using their index. The index of the first item in a list is 0, and the index of the last item is the length of the list minus 1. For example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # prints "apple"
print(fruits[1]) # prints "banana"
print(fruits[2]) # prints "cherry"
You can also use negative indices to access items from the end of the list. For example:
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # prints "cherry"
print(fruits[-2]) # prints "banana"
print(fruits[-3]) # prints "apple"