In Python, a sequence is a type of object that holds multiple items of data, organized in a specific order. This means each item in the sequence has a position or index, and the items are stored one after another, like elements in a line.
Python provides several types of sequences, the most common being:
- Lists
- Tuples
Python lists are one of the most versatile and widely used data structures in the language. They are ordered collections of items that are defined by enclosing elements in square brackets, like this: [ ]. The primary features of Python lists include their mutability and dynamic nature. This means that the contents of a list can be changed after its creation—elements can be added, removed, or modified. Lists can store items of any data type, including other lists, making them incredibly flexible for handling a variety of data structures.
The purposes of Python lists are broad and include storing sequences of items, such as a collection of numbers, strings, objects, or even mixed types. They are particularly useful for implementing stacks, queues, and other collections. Lists are also essential for iterating over elements using loops, applying operations to each element, and comprehending operations that produce new lists based on existing ones.
One of the standout features of Python lists compared to lists in other programming languages is their dynamic sizing. In languages like C++ or Java, arrays have a fixed size defined at the time of their creation. In contrast, Python lists automatically resize as elements are added or removed, managed internally by the Python runtime. This flexibility removes the need for manual memory management, simplifying development.
Python lists have the following characteristics:
- Lists are used to store multiple items in a single variable.
- Lists are created using square brackets.
Example:
|
- Lists are one of the four built-in data types in Python for storing collections of data. The other three are Tuples, Sets, and Dictionaries, each with its own unique properties and uses.
- List items are indexed, with the first item having an index of [0], the second item an index of [1], and so on.
Example:
|
- List items are ordered, changeable, and allow duplicate values.
- When we say that Python lists are ordered, it means that the items in a list have a defined sequence, and that sequence will remain consistent unless explicitly changed.
For example, in the fruits list, "apple" is always the first item, "banana" is the second, and "cherry" is the third.
If you add new items to a list, they will be placed at the end. For instance:
fruits = ["apple", "banana", "cherry"] |
The list is changeable, which means you can modify it after creation. You can change, add, or remove items as needed. Here are some examples:
Changing an item:
|
Adding an item:
|
Removing an item:
|
Since lists are indexed, you can have items with the same value. Lists allow duplicate values, which can be useful in many scenarios. For example:
|
This will output:
['apple', 'banana', 'cherry', 'apple', 'cherry'] |
In this list, "apple" and "cherry" appear twice. Each occurrence is considered a separate item in the list, maintaining their positions and order.
The len() function
You can use the len() function to determine how many items a list contains.
|
Data Types of List Items
Python lists are very flexible and can contain items of any data type, even within the same list. This makes them incredibly versatile for various programming tasks.
Here are some examples to illustrate this concept:
List of Integers:
|
List of Strings:
|
List of Mixed Data Types:
|
In the above example, the list contains an integer (1), a string ("apple"), a float (3.14), and a boolean (True).
The list() Constructor
The list() constructor in Python is a built-in function that creates a new list. It can be used to create an empty list or to convert other iterable types (such as strings, tuples, or sets) into a list.
Here are some examples to illustrate how the list() constructor works:
Creating an empty list:
|
Converting a String to a List:
|
Indexing
In Python, lists are indexed, which means each item in the list has a specific position, known as an index. The index is used to access individual items within the list.
Here are some key points and examples to help you understand list indexing in Python:
(Zero-Based Indexing)
Python lists use zero-based indexing, meaning the first item in the list has an index of 0, the second item has an index of 1, and so on.
|
(Negative Indexing)
Python also supports negative indexing, where -1 refers to the last item, -2 refers to the second-last item, and so on.
|
(Accessing and Modifying List Items)
You can access individual items in a list using their index.
|
(IndexError)
Attempting to access an index that is out of the range of the list will result in an IndexError.
|
(Finding the Index of an Item)
You can find the index of the first occurrence of an item using the index() method. If the item is not found, it raises a ValueError.
|
Slicing
Slicing in Python allows you to access a subset of items from a list. This is done by specifying a start, stop, and step index within square brackets. The syntax for slicing is list[start:stop:step].
Here are some key points and examples to help you understand list slicing:
(Slicing with Start and Stop)
|
This slice starts at index 1 and stops before index 4, so it includes items at indexes 1, 2, and 3.
(Omitting Start or Stop)
|
- numbers[:4] starts from the beginning of the list and stops before index 4.
- numbers[3:] starts from index 3 and goes to the end of the list.
(Specifying a Step)
|
This slice starts at index 1, stops before index 6, and includes every second item.
(Using a Negative Step)
|
This slice reverses the list by starting from the end and stepping backwards.
(Using Negative Indices)
|
This slice starts at the fifth last item and stops before the second last item.
The in Keyword
The in keyword in Python is used to check if a specific item exists in a list (or any other iterable, like a string or tuple). It returns True if the item is found and False otherwise. This is a very convenient and readable way to perform membership tests.
Here are some examples to illustrate how it works:
(Checking for an item in a List)
|
In this example, "banana" is in the list fruits, so the first check returns True. "orange" is not in the list, so the second check returns False.
(Using in in an if statement)
|
This example shows how you can use the in keyword in an if statement to perform different actions based on whether an item is in the list.
List Methods
- list.append(x)
- Add an item to the end of the list. Similar to a[len(a):] = [x].
- list.extend(iterable)
- Extend the list by appending all the items from the iterable. Similar to a[len(a):] = iterable.
- list.insert(i, x)
- Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
- list.remove(x)
- Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
- list.pop([i])
- Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. It raises an IndexError if the list is empty or the index is outside the list range.
- list.clear()
- Remove all items from the list. Similar to del a[:].
- list.index(x[, start[, end]])
- Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.
- The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
- list.count(x)
- Return the number of times x appears in the list.
- list.sort(*, key=None, reverse=False)
- Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
- list.reverse()
- Reverse the elements of the list in place.
- list.copy()
- Return a shallow copy of the list. Similar to a[:].
The insert() Function
The insert() function in Python lists is used to add an item at a specified index. Unlike the append() function, which adds an item to the end of the list, insert() allows you to place the item at any position within the list. The syntax for insert() is list.insert(index, item), where index is the position at which the item will be inserted, and item is the element you want to add to the list.
Here are some examples to illustrate how insert() works:
(Inserting at a Specific Index)
|
The output will be:
['apple', 'orange', 'banana', 'cherry'] |
In this example, "orange" is inserted at index 1, shifting "banana" and "cherry" one position to the right.
(Inserting with Negative Indices)
|
The output will be:
['cat', 'dog', 'hamster', 'rabbit'] |
Using a negative index -1 inserts "hamster" just before the last item.
List Comprehension
List comprehensions in Python provide a concise way to create lists. They are often more readable and faster than using traditional for-loops and append() calls to construct lists. A list comprehension consists of brackets containing an expression followed by a for clause, and optionally additional for or if clauses.
The syntax can be written as:
[expression for item in iterable if condition]
(Creating a list of squares)
|
The output will be:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] |
This list comprehension generates a list of squares of numbers from 0 to 9.
(Filtering with a Condition)
|
The output will be:
[0, 2, 4, 6, 8] |
This creates a list of even numbers from 0 to 9 by including only those numbers that satisfy the condition x % 2 == 0.
The sort() function
The sort() method in Python is used to sort the elements of a list in place, meaning it modifies the original list. By default, it sorts the list in ascending order, but you can customize the sorting order by providing additional parameters.
Here are some key points and examples to illustrate how the sort() function works:
(Sorting a List of Numbers)
|
The output will be:
[1, 2, 5, 5, 6, 9] |
This sorts the list of numbers in ascending order.
(Sorting a List of Strings)
|
The output will be:
['apple', 'banana', 'cherry', 'date'] |
This sorts the list of strings alphabetically.
(Sorting in Descending Order)
|
The output will be:
[9, 6, 5, 5, 2, 1] |
Setting the reverse parameter to True sorts the list in descending order.
Example Use Case - Total Sales Calculation
Write a program that asks the user to enter a store’s sales for each day of the week. The amounts should be stored in a list. Use a loop to calculate the total sales for the week and display the result.
Detailed Instructions
- Input Sales Data:
- Prompt the user to enter sales amounts for each day of the week (Monday to Sunday).
- Store each day's sales in a list.
- Calculate Total Sales:
- Use a loop to iterate through the list and calculate the total sales for the week.
- Display Total Sales:
- Print the total sales amount.
Example Output: