Lists in Python
In Python, lists are a versatile and commonly used data structure that allows you to store an ordered collection of items. Lists can hold items of different data types, including numbers, strings, objects, and even other lists.
Creating a List in Python
In Python, lists are constructed using square brackets [ ], and the items within the list are separated by commas.
Syntax for Creating a List:
- You define the list with a name.
- Use square brackets to enclose the list items.
- Separate the items with commas.
Example:
In this example, each item in the list is a string representing the name of colors. When you print the list, it looks exactly like the list you created.
Creating Different Types of Lists
You can create lists containing different types of data. A list can even be empty.
Examples:
- numbers_listcontains only numbers.
- mixed_listcontains a string, a float, an integer, and another list.
- empty_listis an example of an empty list, and its type is still a list.
You can store any item in a list - strings, numbers, objects, or even other lists. The items in a list don't need to be of the same type, meaning a list can be heterogeneous.
Basic List Operations
Python provides various operations to work with lists. You can concatenate lists, repeat them, or check for the presence of an item.
Examples:
- Concatenation: The +operator is used to combine two lists into a new list.
- Repetition: The *operator repeats the items in the list a specified number of times.
- Comparison: You can compare two lists using the ==operator, which returnsTrueif the lists are identical, andFalseotherwise.
Membership Operators
You can check whether an item is in a list using the in and not in operators, which return a Boolean value.
Example:
- inoperator returns- Trueif the item is present in the list, and- Falseotherwise.
The list() Function
The list() function in Python is used to create a list from a sequence like a string, tuple, or another list. If no sequence is provided, it creates an empty list.
Example:
- Converting a string to a list: The list()function splits the string into its individual characters and creates a list.
- Concatenating a list with a string: You cannot directly concatenate a string with a list; you must first convert the string to a list.
Indexing and Slicing in Lists
In Python, lists are ordered collections of items. You can access individual items and extract sublists using indexing and slicing techniques.
Indexing
Indexing allows you to access specific elements in a list. The index is an integer value enclosed in square brackets [ ], with indexing starting from 0.
Syntax for Accessing an Item:
Examples:
- Positive Indexing: The index 0refers to the first item,1to the second, and so on.
- IndexError: If you try to access an index that does not exist, Python raises an IndexError.
Negative Indexing: Allows you to access items from the end of the list. The index -1 refers to the last item, -2 to the second-to-last item, etc.
Example:
Modifying Items
Lists are mutable, meaning their contents can be changed after creation. You can modify the items in a list by assigning new values to specific indices. Additionally, assigning a list to a new variable creates a reference to the same list, not a copy.
Examples:
Explanation:
- Changing an Item by Positive Index: The first item, "Ford", is replaced with"Chevrolet"using index0.
- Changing an Item by Positive Index: The third item, "Honda", is replaced with"Tesla"using index2.
- Changing an Item by Negative Index: The last item, "Tesla", is replaced with"Nissan"using negative index-1.
Variable Assignment and Modification
When you assign a list to a new variable, both variables refer to the same list object in memory. Changes made through one variable are reflected in the other.
Example:
Variable Assignment: When cars is assigned to new_cars, both variables point to the same list. Therefore, changes made through new_cars are also seen when accessing cars.
Slicing in Python
Slicing is a powerful feature in Python that lets you extract specific portions of a list (or other sequence types like strings and tuples). You achieve this by specifying a start and stop index, and optionally, a step value. The resulting slice includes elements from the start index up to, but not including, the stop index.
Syntax for Slicing:
- start: The index where the slice begins. If omitted, it defaults to 0 (the beginning of the list).
- stop: The index where the slice ends. The element at this index is not included in the slice. If omitted, it defaults to the length of the list (the very end).
- step: The number of indices to jump between elements. If omitted, it defaults to 1 (include every element).
Examples using Positive Indices:
Slicing with Negative Indices
You can also use negative indices for both start and stop. Negative indices count backward from the end of the list, where -1 represents the last element.
Built-In Functions Used on Lists
Python provides several built-in functions that you can use with lists. These functions allow you to perform various operations such as finding the length, summing up numbers, and sorting.
| Function | Description | 
|---|---|
| len() | Returns the number of items in the list. | 
| sum() | Returns the sum of all numerical items in the list. | 
| max() | Returns the maximum value in the list. | 
| min() | Returns the minimum value in the list. | 
| any() | Returns Trueif any item in the list isTrue(or evaluates toTrue). | 
| all() | Returns Trueif all items in the list areTrue(or evaluate toTrue). | 
| sorted() | Returns a new list that is a sorted version of the original list. The original list remains unchanged. | 
Examples
1. len() Function:
- The len()function returns the number of items in thecolorslist.
2. sum() Function:
- The sum()function calculates the total of all numerical items in thenumberslist.
3. max() and min() Functions:
- max()returns the highest value, and- min()returns the lowest value in the list.
4. any() Function
Explanation:
The any() function checks if at least one element in an iterable (such as a list) is true. It returns True if any element evaluates to True, and False otherwise. In Python, values considered False are:
- False
- None
- Numeric zero (0)
- Empty sequences (e.g., "",[],())
- Empty mappings (e.g., {})
In the example, since there are 1 (which are True), any([1, 1, 0, 0, 1, 0]) returns True.
5. all() Function
Explanation:
The all() function checks if every element in an iterable is true. It returns True only if all elements evaluate to True. If any element is False, the function returns False.
- In the first example, all elements are 1, which areTrue, soall([1, 1, 1, 1])returnsTrue.
- In the second example, the presence of 0(which isFalse) makesall([1, 0, 1, 1])returnFalse.
6. sorted() Function:
- The sorted()function returns a new list that is sorted, leaving the originalcolorslist unchanged. In the case of string items in the list, they are sorted based on their ASCII values.
List Methods
Python lists come with a variety of built-in methods that allow you to perform operations like adding, removing, and modifying items.
| Method | Syntax | Description | 
|---|---|---|
| append() | list.append(item) | Adds a single item to the end of the list. | 
| count() | list.count(item) | Counts the number of occurrences of an item in the list. | 
| insert() | list.insert(index, item) | Inserts an item at a specified index, shifting subsequent items to the right. | 
| extend() | list.extend(list2) | Extends the list by appending elements from another list. | 
| index() | list.index(item) | Returns the index of the first occurrence of an item. Raises ValueErrorif not found. | 
| remove() | list.remove(item) | Removes the first occurrence of an item. Raises ValueErrorif not found. | 
| sort() | list.sort() | Sorts the items of the list in place. | 
| reverse() | list.reverse() | Reverses the items of the list in place. | 
| pop() | list.pop([index]) | Removes and returns the item at the specified index. Returns the last item if index is omitted. | 
Examples
1. append() Method:
- Adds 'una' to the end of the citieslist.
2. count() Method:
- Counts how many times 'kangra' appears in the list.
3. insert() Method:
- Inserts 'una' at index 1.
4. extend() Method:
- Appends items from more_citiesto the end of thecitieslist.
5. index() Method:
- Returns the index of the first occurrence of 'dharamshala'.
6. remove() Method:
- Removes the first occurrence of 'dharamshala'.
7. sort() Method:
- Sorts the list in alphabetical order.
8. reverse() Method:
- Reverses the order of items in the list.
9. pop() Method:
- Removes and returns the last item from the list. If an index is provided, it removes and returns the item at that index.
Populating Lists with Items
Populating lists in Python is straightforward. You can start with an empty list and use methods like append() or extend() to add items.
Using append() Method:
The append() method adds a single item to the end of the list.
Using extend() Method:
The extend() method adds multiple items to the end of the list from another iterable (like another list).
Traversing Lists
You can use loops to traverse through a list and access each item. The most common way is using a for loop.
Example:
This will print each country in the list.
Output:
Nested Lists
A nested list is a list within another list. You can create and access nested lists using multiple levels of indexing.
Example of a Nested List:
Traversing Nested Lists
You can traverse through nested lists using nested for loops.
Example:
This will print each country from each continent in the nested list.
Output
The del Statement in Python
The del statement in Python is used to remove items from a list based on their index, slices, or even clear the entire list. Unlike the pop() function, which returns the value of the removed item, the del statement does not return any value. Here’s how you can use the del statement:
1. Removing a Single Item
You can use del to remove an item from a list based on its index.
Example:
In this example, the item 1 at index 0 is removed from the list.
2. Removing a Slice of Items
You can also use del to remove a range of items (a slice) from a list.
Example:
In this example, the items 3 and 4 (from index 2 to 4) are removed from the list.
3. Clearing the Entire List
To remove all items from a list, you can use del with a slice that includes all items.
Example:
Here, the entire list is cleared, leaving it empty.