Creating and Accessing Lists
In Python, a list is a collection of items that can be of different data types. Lists are a versatile data type that can be used to store and manipulate data in a variety of ways. In this article, we will introduce you to the basics of working with lists in Python.
To create a list in Python, you can enclose a comma-separated list of items in square brackets (). For example:
numbers = [1, 2, 3, 4, 5] words = ["apple", "banana", "cherry"] mixed = [1, "apple", 2.5, True]
In this example, we have created three lists: “numbers”, “words”, and “mixed”. The “numbers” list contains a series of integers, the “words” list contains a series of strings, and the “mixed” list contains a mix of integers, strings, and a boolean value.
Accessing List Items
To access the items in a list, you can use the index of the item in square brackets. In Python, list indexes start at 0, so the first item in a list has an index of 0, the second item has an index of 1, and so on.
numbers = [1, 2, 3, 4, 5] print(numbers) # prints 1 print(numbers) # prints 2 print(numbers) # prints 3
You can also use negative indexes to access items from the end of the list. For example, the index “-1” refers to the last item in the list, “-2” refers to the second-to-last item, and so on.
numbers = [1, 2, 3, 4, 5] print(numbers[-1]) # prints 5 print(numbers[-2]) # prints 4 print(numbers[-3]) # prints 3
Modifying List Items
To modify an item in a list, you can assign a new value to the item using its index. For example:
numbers = [1, 2, 3, 4, 5] numbers = 6 print(numbers) # prints [1, 2, 6, 4, 5]
In this example, we have modified the third item in the “numbers” list (which has an index of 2) and replaced it with the value 6.
Lists are a useful data type in Python that allow you to store and manipulate a collection of items. By understanding how to create and access lists, as well as how to modify list items, you will be able to use lists effectively in your Python programs.
In our “Introduction to Python” course, we will delve deeper into working with lists and cover more advanced topics such as slicing and list comprehension. We hope you will join us on this journey!
Here are some exercises with solutions to help you practice what you just learned: