⬅ Previous Topic
Introduction to Python CollectionsNext Topic ⮕
Python Dictionaries⬅ Previous Topic
Introduction to Python CollectionsNext Topic ⮕
Python DictionariesIn real life, we often need to keep track of multiple items together. For example, a list of groceries, names of your friends, or favorite movies.
In Python, we use something called a list to store many items in one place.
A list is a collection of items. These items are stored in a specific order, and you can add, change, or remove items whenever you want.
Think of it like a shopping list you can edit!
You can create a list by putting items inside square brackets [ ]
, separated by commas.
fruits = ["apple", "banana", "cherry"]
fruits
is the name of the list.Lists are used everywhere when you need to store multiple values together. Some examples:
Creating a new list:
colors = ["red", "green", "blue"]
We can read items by their position (called an index). Remember, counting starts from 0!
print(colors[0])
Output:
red
Here, colors[0]
gives us the first item, which is "red".
We can change an item in the list:
colors[1] = "yellow"
print(colors)
Output:
['red', 'yellow', 'blue']
We changed the second item ("green") to "yellow".
We can remove items from the list using del
:
del colors[2]
print(colors)
Output:
['red', 'yellow']
We deleted the third item ("blue"). Now only two colors are left.
Use append()
to add a new item at the end:
colors.append("purple")
print(colors)
Output:
['red', 'yellow', 'purple']
Use len()
to find how many items are in the list:
print(len(colors))
Output:
3
Now that you know lists, you're ready to start managing collections of data in your Python programs!
⬅ Previous Topic
Introduction to Python CollectionsNext Topic ⮕
Python DictionariesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.