This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Max
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']
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
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']
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)
output:
apple
banana
cherry
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Max
Max | Sciencx (2023-02-18T17:46:00+00:00) Python Lists tutorial. Retrieved from https://www.scien.cx/2023/02/18/python-lists-tutorial/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.