PYTHON LISTS
In Python, a list is a versatile and commonly used data structure that allows you to store and manipulate collections of items. Lists are ordered, mutable, and can contain elements of different data types. Here’s a breakdown of Python lists:
Characteristics of Lists:
1. Ordered:
– Lists maintain the order of elements as they are added.
– You can access elements in a list using their indices.
2. Mutable:
– Lists can be modified after creation.
– You can change, add, or remove elements from a list.
3. Heterogeneous Elements:
– Lists can contain elements of different data types, including integers, floats, strings, and even other lists.
Here are some illustrative code examples demonstrating the characteristics of lists and how to create them:
1. Ordered:
Lists maintain the order of elements as they are added. You can access elements in a list using their indices.
“`python
# Define a list of colors
colors = [“red”, “green”, “blue”, “yellow”]
# Print the list of colors
print(“Original List:”, colors)
# Add a new color to the list
colors.append(“orange”)
# Print the updated list of colors
print(“Updated List:”, colors)
“`
Output:
“`
Original List: [‘red’, ‘green’, ‘blue’, ‘yellow’]
Updated List: [‘red’, ‘green’, ‘blue’, ‘yellow’, ‘orange’]
“`
In this example, the colors are added to the list in a specific order: red, green, blue, and yellow. When we append “orange” to the list, it gets added to the end, maintaining the order of the elements as they were originally added. This demonstrates how lists in Python preserve the order of elements.
2. Mutable:
Lists can be modified after creation. You can change, add, or remove elements from a list.
“`python
# Define a list of numbers
numbers = [1, 2, 3, 4, 5]
# Print the original list
print(“Original List:”, numbers)
# Modify an element at index 2
numbers[2] = 10
# Print the modified list
print(“Modified List:”, numbers)
# Add a new element to the list
numbers.append(6)
# Print the list after adding a new element
print(“List after adding element:”, numbers)
# Remove an element from the list
removed_element = numbers.pop(3)
# Print the list after removing an element
print(“List after removing element:”, numbers)
print(“Removed Element:”, removed_element)
“`
Output:
“`
Original List: [1, 2, 3, 4, 5]
Modified List: [1, 2, 10, 4, 5]
List after adding element: [1, 2, 10, 4, 5, 6]
List after removing element: [1, 2, 10, 5, 6]
Removed Element: 4
“`
In this example, we start with a list of numbers `[1, 2, 3, 4, 5]`. We modify an element at index 2, add a new element to the list, and remove an element from the list using various list methods. This demonstrates how lists in Python can be modified after creation, highlighting their mutability.
3. Heterogeneous Elements:
Lists can contain elements of different data types, including integers, floats, strings, and even other lists.
“`python
# Define a list with heterogeneous elements
mixed_list = [10, “hello”, 3.14, True, [1, 2, 3]]
# Print the list
print(“Mixed List:”, mixed_list)
# Access elements of different data types
print(“Element at index 0 (Integer):”, mixed_list[0])
print(“Element at index 1 (String):”, mixed_list[1])
print(“Element at index 2 (Float):”, mixed_list[2])
print(“Element at index 3 (Boolean):”, mixed_list[3])
print(“Element at index 4 (List):”, mixed_list[4])
“`
Output:
“`
Mixed List: [10, ‘hello’, 3.14, True, [1, 2, 3]]
Element at index 0 (Integer): 10
Element at index 1 (String): hello
Element at index 2 (Float): 3.14
Element at index 3 (Boolean): True
Element at index 4 (List): [1, 2, 3]
“`
In this example, we define a list called `mixed_list` that contains elements of different data types: integer (`10`), string (`”hello”`), float (`3.14`), boolean (`True`), and another list (`[1, 2, 3]`). This demonstrates how lists in Python can accommodate heterogeneous elements within the same data structure.
Overall, lists in Python are versatile data structures that allow you to store and manipulate collections of items. They maintain order, are mutable, and can contain elements of different data types. Their flexibility makes them widely used in Python programming for various tasks and applications.
Â
ACCESSING ITEMS IN PYTHON LISTS
Accessing items in lists in Python involves using various syntax elements to access and manipulate list elements. Here’s a breakdown of the syntax for navigating lists:
1. Accessing Single Items:
To access a single item in a list, use square brackets `[]` with the index of the item you want to access. Python uses zero-based indexing.
“`python
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 30
“`
2. Slicing:
Slicing allows you to extract a portion of the list using the syntax `[start:stop:step]`, where `start` is the index to start slicing from, `stop` is the index to stop slicing (exclusive), and `step` is the step size.
“`python
my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # Output: [20, 30, 40]
print(my_list[:3]) # Output: [10, 20, 30]
print(my_list[2:]) # Output: [30, 40, 50]
print(my_list[::2]) # Output: [10, 30, 50] (every second element)
“`
3. Negative Indexing:
Negative indexing allows you to access elements from the end of the list.
“`python
my_list = [10, 20, 30, 40, 50]
print(my_list[-1]) # Output: 50 (last element)
“`
4. List Length:
The `len()` function returns the number of elements in the list.
“`python
my_list = [10, 20, 30, 40, 50]
print(len(my_list)) # Output: 5
“`
5. Checking for Membership:
You can check if an element is present in a list using the `in` keyword.
“`python
my_list = [10, 20, 30, 40, 50]
print(20 in my_list) # Output: True
“`
6. Iterating Over a List:
You can use a `for` loop to iterate over the elements of a list.
“`python
my_list = [10, 20, 30, 40, 50]
for item in my_list:
print(item)
“`
7. Modifying List Elements:
Lists are mutable, meaning you can modify their elements.
“`python
my_list = [10, 20, 30, 40, 50]
my_list[2] = 35 # Modify the third element
print(my_list) # Output: [10, 20, 35, 40, 50]
“`
Understanding these navigation techniques is essential for effectively working with lists in Python.
ALL AVAILABLE FUNCTIONS IN PYTHON LIST
# Get all available functions of lists
list_functions = [func for func in dir(list) if not func.startswith(“__”)]
# Print the list of functions
print(list_functions)
Â
SOME COMMON INBUILT FUNCTIONS IN PYTHON LISTS
Sure, here are some common built-in functions used with lists in Python:
1. `len()`:
– Returns the number of elements in the list.
“`python
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
“`
2. `max()`:
– Returns the largest element in the list.
“`python
my_list = [1, 3, 5, 2, 4]
print(max(my_list)) # Output: 5
“`
3. `min()`:
– Returns the smallest element in the list.
“`python
my_list = [1, 3, 5, 2, 4]
print(min(my_list)) # Output: 1
“`
4. `sum()`:
– Returns the sum of all elements in the list.
“`python
my_list = [1, 2, 3, 4, 5]
print(sum(my_list)) # Output: 15
“`
5. `sorted()`:
– Returns a new sorted list from the elements of the given iterable.
“`python
my_list = [5, 2, 1, 3, 4]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 3, 4, 5]
“`
6. `list()`:
– Returns a list object. Used to convert other iterable objects (like tuples or strings) into lists.
“`python
my_tuple = (1, 2, 3)
new_list = list(my_tuple)
print(new_list) # Output: [1, 2, 3]
“`
7. `any()`:
– Returns `True` if any element in the iterable is `True`. If the iterable is empty, it returns `False`.
“`python
my_list = [False, False, True, False]
print(any(my_list)) # Output: True
“`
8. `all()`:
– Returns `True` if all elements in the iterable are `True`. If the iterable is empty, it returns `True`.
“`python
my_list = [True, True, True, False]
print(all(my_list)) # Output: False
“`
9. `enumerate()`:
– Returns an enumerate object containing tuples of indices and corresponding values from the iterable.
“`python
my_list = [‘a’, ‘b’, ‘c’]
for index, value in enumerate(my_list):
print(index, value)
# Output:
# 0 a
# 1 b
# 2 c
“`
10. `reversed()`:
– Returns a reverse iterator over the values of the iterable.
“`python
my_list = [1, 2, 3, 4, 5]
reversed_list = reversed(my_list)
print(list(reversed_list)) # Output: [5, 4, 3, 2, 1]
“`
11. `zip()`:
– Returns an iterator that aggregates elements from multiple iterables into tuples.
“`python
list1 = [1, 2, 3]
list2 = [‘a’, ‘b’, ‘c’]
zipped_list = zip(list1, list2)
print(list(zipped_list)) # Output: [(1, ‘a’), (2, ‘b’), (3, ‘c’)]
“`
12. `sorted()`:
– Returns a new sorted list from the elements of the iterable.
“`python
my_list = [4, 2, 1, 3]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 3, 4]
“`
13. `min()`:
– Returns the minimum value from the elements of the iterable.
“`python
my_list = [4, 2, 1, 3]
print(min(my_list)) # Output: 1
“`
14. `max()`:
– Returns the maximum value from the elements of the iterable.
“`python
my_list = [4, 2, 1, 3]
print(max(my_list)) # Output: 4
“`
15. `sum()`:
– Returns the sum of all elements in the iterable.
“`python
my_list = [1, 2, 3, 4, 5]
print(sum(my_list)) # Output: 15
“`
16. `filter()`:
– Returns an iterator yielding those items of the iterable for which the function returns true.
“`python
my_list = [1, 2, 3, 4, 5]
filtered_list = filter(lambda x: x % 2 == 0, my_list)
print(list(filtered_list)) # Output: [2, 4]
“`
These are some of the common built-in functions used to manipulate and work with lists in Python.
EXERCISES
1. List Manipulation:
– Create a list containing numbers from 1 to 10.
– Append the number 11 to the list.
– Insert the number 0 at the beginning of the list.
– Remove the number 5 from the list.
– Print the modified list.
2. List Slicing:
– Create a list containing the first 10 even numbers.
– Print the first 5 elements of the list.
– Print the last 3 elements of the list.
– Print every second element of the list.
3. List Comprehension:
– Create a list containing the squares of numbers from 1 to 10 using list comprehension.
– Create a list containing only the even numbers from the original list.
4. Nested Lists:
– Create a nested list containing two lists: `[1, 2, 3]` and `[4, 5, 6]`.
– Access the element `5` from the nested list.
– Change the second element of the first list to `10`.
5. List Operations:
– Create two lists: `[1, 2, 3]` and `[4, 5, 6]`.
– Concatenate the two lists and store the result in a new list.
– Repeat the first list three times and store the result in a new list.
– Check if the number `7` is present in any of the lists.
6. List Iteration:
– Create a list containing the names of five fruits.
– Use a `for` loop to print each fruit name in the list.
7. List Length:
– Create a list of your favorite movies.
– Print the total number of movies in the list.
8. List Sorting:
– Create a list of random numbers.
– Sort the list in ascending order.
– Sort the list in descending order.
9. List Removal:
– Create a list of colors.
– Remove the last two colors from the list.
– Remove a specific color from the list.
10. List Clearing:
– Create a list of numbers.
– Clear the list so that it becomes empty.
These exercises cover various aspects of list manipulation, iteration, comprehension, and operations in Python. They should help reinforce your understanding of lists and their functionalities.