Lists are one of the most commonly used data structures in Python. They allow you to store and organize multiple items in a single variable. In this guide, we will learn how to create lists and explore some basic functions associated with them.
Python Basics: Lists
Lists are one of the most commonly used data structures in Python. They allow you to store and organize multiple items in a single variable. In this guide, we will learn how to create lists and explore some basic functions associated with them.
Creating a List:
To create a list in Python, you can enclose a comma-separated sequence of items within square brackets ([]). Example:
In the above example, we created a list called fruits that contains four items: 'apple', 'banana', 'orange', and 'mango'. Each item in the list is separated by a comma.
Accessing List Items:
You can access individual items in a list using their index. In Python, list indices start from 0. To access an item, you can use the name of the list followed by the index enclosed in square brackets. Example:
In the above example, we accessed the first item in the fruits list using the index 0 and the third item using the index 2.
List Length:
You can determine the length of a list, i.e., the number of items in a list, using the len() function. Example:
The len() function returns the total number of items in the fruits list, which is 4 in this case.
Modifying List Items:
Lists are mutable, which means you can change the values of individual items. To modify a list item, you can assign a new value to the item at a specific index. Example:
In the above example, we modified the second item (index 1) in the fruits list and changed it from 'banana' to 'grape'. The resulting list now contains the updated value.
List Functions:
Python provides several functions that are commonly used with lists. Let's explore a few of them:
These are just a few examples of the functions you can use with lists. There are many more functions available to perform various operations on lists.
Lists are versatile and powerful data structures in Python. They allow you to store and manipulate collections of items efficiently. Understanding the basics of lists will help you write more complex and dynamic programs.