DEV Community

Max
Max

Posted on • Updated on

Python Lists tutorial

Python list is a collection of items of any data type. Lists are mutable, which means they can be modified. Python provides various operations that can be performed on lists like insertion, deletion, and sorting.

Creating a List

A list can be created in Python by enclosing a sequence of items inside square brackets [], separated by commas.

# empty list
my_list = []

# list with items
fruits = ['apple', 'banana', 'cherry']
Enter fullscreen mode Exit fullscreen mode

Accessing List Items

Items in a list can be accessed by using the index value. The first item in the list has an index of 0, the second item has an index of 1, and so on.

fruits = ['apple', 'banana', 'cherry']
print(fruits[1])  # Output: banana
Enter fullscreen mode Exit fullscreen mode

Modifying List Items

List items can be modified by accessing the item using its index and assigning a new value.

fruits = ['apple', 'banana', 'cherry']
fruits[1] = 'orange'
print(fruits)  # Output: ['apple', 'orange', 'cherry']
Enter fullscreen mode Exit fullscreen mode

List Loop

A for loop can be used to iterate through the items in a list.

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

output:

apple
banana
cherry
Enter fullscreen mode Exit fullscreen mode

Explore Other Related Articles

Python dictionaries comprehension tutorial
Python comparison between normal for loop and enumerate
Python if-else Statements Tutorial
Python set tutorial
Python tuple tutorial

Top comments (0)