When starting with programming, one of the most fundamental concepts to master is the list. Python lists are incredibly versatile data structures that allow you to store and organize collections of items. Whether it’s a shopping list or a series of numbers, understanding how to manipulate lists is a cornerstone of effective coding.
Table of Contents
💻 Creating and Accessing Lists
A list in Python is an ordered collection of items enclosed in square brackets. You can create one easily:
shopping_list = ["milk", "bread", "baked beans"]
Lists are dynamic, meaning you can add or remove items after creation. You can access any item in the list by its numerical index, which starts from zero.
- To get the first item (“milk”), you would use
shopping_list[0]
. - To get the third item (“baked beans”), you would use
shopping_list[2]
.
💻 Stacks vs. Queues: LIFO and FIFO
The way you add and remove items from a list can give it special properties, often described as Stacks or Queues.
- Stack (LIFO – Last-In, First-Out): Think of a stack of plates. The last one you add is the first one you take off. In Python, you can simulate this using
.append()
to add to the end and.pop()
to remove from the end.# Add 'soup' to the end of the list shopping_list.append("soup") # Remove and return the last item ('soup') last_item = shopping_list.pop()
- Queue (FIFO – First-In, First-Out): Think of a line at a supermarket. The first person in line is the first to be served. You can simulate this by using
.append()
to add to the end and.pop(0)
to remove from the beginning.# Remove and return the first item ('milk') first_item = shopping_list.pop(0)
More Topics
- Python Project Guide: NumPy & SciPy: For Science!
- Python Project Guide: Times, Dates & Numbers
- Python Project Guide: Making Scripts
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Using Functions in Python 3
- Python Project Guide: How to Get Started with Python 3
- Coding Concepts Explained: Avoid Common Coding Mistakes