List Manipilation
List Manipilation
given as [1, 3, 5]
(i) lst * 3 and lst *= 3
(ii) lst + 3 and lst += [3]
ANS: Let's break down the differences between the two pairs of expressions.
- **`lst * 3`:** This expression creates a new list by repeating the original list `lst` three times. For
`lst = [1, 3, 5]`, the result would be:
[1, 3, 5, 1, 3, 5, 1, 3, 5]
- **`lst *= 3`:** This modifies the original list in place, repeating its elements three times. The `lst`
itself becomes:
[1, 3, 5, 1, 3, 5, 1, 3, 5]
In both cases, the result is the same for the given example, but the first creates a new list while the
second modifies the existing list.
**`lst + 3`:** This expression raises a `TypeError` because you cannot concatenate an integer (3)
directly to a list. The operation is invalid.
**`lst += [3]`:** This modifies the original list by appending the value `3` as an element of a new list.
After this operation, `lst` becomes:
[1, 3, 5, 3]
In summary:
- The first pair (`*` vs. `*=`) behaves similarly in terms of outcome but differs in how they operate on
the list.
- The second pair (`+` vs. `+=`) shows a type error with the first expression and successfully modifies
the list with the second.
1. L1 == L2
2. L1.upper( )
3. L1[3].upper( )
4. L2.upper( )
5. L2[1].upper( )
6. L2[1][1].upper( )
ANS: Let's evaluate each expression and see if it will cause an error:
1. **`L1 == L2`**:
- This compares the two lists. Since their contents and structure are different (`L1` has four strings
while `L2` has a string and a nested list), this will return `False`, but it won't cause an error.
2. **`L1.upper()`**:
- This will cause an `AttributeError` because `L1` is a list, and lists do not have an `upper()` method.
3. **`L1[3].upper()`**:
- This accesses the fourth element of `L1`, which is the string `'List'`, and calls `upper()` on it. This
will return `'LIST'` without causing an error.
4. **`L2.upper()`**:
- This will cause an `AttributeError` for the same reason as `L1.upper()`: `L2` is also a list and does
not have an `upper()` method.
5. **`L2[1].upper()`**:
- This accesses the second element of `L2`, which is the nested list `["is", "another"]`. Since a list
does not have an `upper()` method, this will also raise an `AttributeError`.
6. **`L2[1][1].upper()`**:
- This accesses the second element of the nested list `["is", "another"]`, which is the string
`"another"`, and calls `upper()` on it. This will return `'ANOTHER'` without causing an error.
Summary of errors:
- `L1.upper()`
- `L2.upper()`
- `L2[1].upper()`
5.Given a list L1 = [3, 4.5, 12, 25.7, [2, 1, 0, 5], 88], which function
can change the list to:
1. [3, 4.5, 12, 25.7, 88]
2. [3, 4.5, 12, 25.7]
3. [ [2, 1, 0, 5], 88]
ANS: You can achieve the desired changes to the list `L1` using the `remove()` method or by slicing.
Here are the functions you can use for each transformation:
L1.remove([2, 1, 0, 5])
L1 = L1[4:] # Slicing to keep the last two elements (the nested list and 88)
Summary of methods:
- **`remove()`**: Removes the first occurrence of a specified value from the list.
- **`pop()`**: Removes and returns an element at a specified index (or the last element if no index is
provided).
Make sure to execute these operations in the right order based on your needs!
2. **`L1.reverse()`**: This method reverses the list in place and returns `None`. It modifies `L1`
directly, so after this call, `L1` becomes `[9, 7, 5, 3, 1]`.
3. **`L1 == L1.reverse()`**:
- The `reverse()` method does not return the reversed list; it returns `None`.
- Therefore, this expression evaluates to `[9, 7, 5, 3, 1] == None`, which is `False`.
4. **`print(L1)`**: This will output the modified list, which is now `[9, 7, 5, 3, 1]`.Final output:
```
False
[9, 7, 5, 3, 1]
```
1. **Initialization**:
```python
```
```python
my_list[2:3] = []
```
- Assigning `[]` to this slice effectively removes the element `'o'` from the list.
```
```
3. **First print statement**:
```python
print(my_list)
```
```
```
```python
my_list[2:5] = []
```
- The slice `my_list[2:5]` refers to the elements at indices 2, 3, and 4, which are `'b'`, `'l'`, and `'e'`.
```
```
```python
print(my_list)
```
```
```
Final output:
```
1. **Initialization**:
```python
```
```python
print(List1.index(18))
```
- The `index()` method returns the index of the first occurrence of the specified value. Here, `18`
first appears at index `1`.
```
```
```python
print(List1.count(18))
```
- The `count()` method returns the number of times a specified value appears in the list. Here, `18`
appears twice.
```2
4. **Appending the count of `13`**:
```python
List1.append(List1.count(13))
```
- The `count(13)` method will return the number of times `13` appears in the list. Here, `13`
appears three times.
- The `append()` method adds this count (which is `3`) to the end of `List1`.
```
```
```python
print(List1)
```
```
```
Final output:
```
```
```python
Odd = [1, 3, 5]
```
```python
```
```
[1, 3, 5, 2, 4, 6]
```
- The index `4` refers to the fifth element (since indexing starts at `0`), which is `4`.
```
```
```python
```
```
```
```
14 - 4 = 10
```
Final output:
```
10
```
1. **Initialization**:
```python
```
- Here, `a`, `b`, and `c` are all assigned separate lists, each containing the elements `[1, 2]`.
```python
print(a == b)
```
- The `==` operator checks for value equality. Since both `a` and `b` contain the same values (`[1,
2]`), this expression evaluates to `True`.
```
True
`..
```python
print(a is b)
- The `is` operator checks for identity, meaning it checks if `a` and `b` refer to the same object in
memory. Since `a` and `b` were created as separate lists, they are different objects, even though
they have the same content.
```
False
```
Final output:
```
True
False
```
11.Predict the output of following two parts. Are the outputs same?
Are the outputs different? Why?
(a)
L1, L2 = [2, 4] , [2, 4]
L3 = L2
L2[1] = 5
print(L3)
(b)
L1, L2 = [2, 4] , [2, 4]
L3 = list(L2)
L2[1] = 5
print(L3)
1. **Initialization**:
```python
L1, L2 = [2, 4], [2, 4]
```
- Here, `L1` and `L2` are two separate lists, each containing `[2, 4]`.
```python
L3 = L2
```
- This line makes `L3` a reference to the same list object as `L2`. Both `L2` and `L3` now point to the
same list in memory.
3. **Modifying `L2`**:
```python
L2[1] = 5
```
- This changes the second element of the list pointed to by both `L2` and `L3` to `5`. Now, both `L2`
and `L3` represent `[2, 5]`.
4. **Printing `L3`**:
```python
print(L3)
```
- Since `L3` references the same list as `L2`, this will output:
```
[2, 5]
```
Part (b)
1. **Initialization**:
```python
```
- Same as part (a), `L1` and `L2` are two separate lists.
```python
L3 = list(L2)
```
- This creates a new list `L3` that is a copy of `L2`. Now, `L3` contains `[2, 4]`, but it is a separate
object in memory.
3. **Modifying `L2`**:
```python
L2[1] = 5
```
- This changes `L2` to `[2, 5]`. However, `L3` remains unchanged since it is a copy.
4. **Printing `L3`**:
```python
print(L3)
```
- Since `L3` is a copy of the original `L2` (before modification), it will output:
```
[2, 4]
```
Comparison of Outputs
### Why?
- In part (a), `L3` is a reference to the same list as `L2`. Modifying `L2` also changes `L3`.
- In part (b), `L3` is a separate copy of `L2`. Modifying `L2` does not affect `L3`.
So, the key difference lies in whether `L3` is a reference to the same list or a copy of it.
1. **Initialization of `L1`**:
```python
```
```python
L2 = L1 + 2
```
- This line will cause a `TypeError`. The `+` operator for lists is used to concatenate two lists, not to
add an integer directly. To add `2` to each element, you would need to use a list comprehension or a
similar method. For example:
```python
L2 = [x + 2 for x in L1]
```
L3 = L1 * 2
```
- This line is correct. The `*` operator for lists duplicates the list, so `L3` will be:
```
```
```python
Idx = L1.index(45)
```
- This line will cause a `ValueError`. The `index()` method raises an error if the specified value is not
found in the list. Since `45` is not in `L1`, this will raise:
```
```
- **Error in Line 2**: `TypeError` because you cannot directly add an integer to a list.
```python
try:
except ValueError:
Idx = None # Handle the error gracefully
```
In this example, `L2` is correctly created, and we handle the potential error with `Idx`.
1. **Initialization of `L1`**:
```python
```
```python
An = L1.remove(41)
```
- This line will cause a `ValueError`. The `remove()` method tries to remove the first occurrence of
the specified value from the list. Since `41` is not in `L1`, the method will raise:
```
```
If you want to avoid the error, you could check if the element exists in the list before trying to
remove it. Here’s a way to handle it:
```python
if 41 in L1:
L1.remove(41)
else:
```
This way, you prevent the error and can handle the situation gracefully.
ANS: Let's analyze the code step by step to identify any errors:
1. **Initialization of `L1`**:
```python
```
```python
An = L1.remove(31)
```
- The `remove()` method removes the first occurrence of the specified value from the list. In this
case, it removes `31` from `L1`.
- However, the `remove()` method does not return the removed value; it returns `None`.
Therefore, `An` will be set to `None`.
3. **Attempting to print `An + 2`**:
```python
print(An + 2)
```
- Since `An` is `None`, attempting to add `2` to `None` will raise a `TypeError`. Specifically, you
will get:
```
```
- **Error in Line 3**: `TypeError` because you cannot add an integer to `None`.
If you want to add `2` to the value that was removed, you could do it this way:
```python
if 31 in L1:
L1.remove(31)
else:
```
In this corrected version, we explicitly store the value `31` before removing it, allowing for the
addition operation to succeed.
14.AFind the errors:
L1 = [3, 4, 5]
L2 = L1 * 3
print(L1 * 3.0)
print(L2)
ANS: Let's analyze the code step by step to identify any errors:
1. **Initialization of `L1`**:
```python
L1 = [3, 4, 5]
```
- This line is correct. `L1` is initialized as a list.
4. **Printing `L2`**:
```python
print(L2)
```
- This line is correct and will output the contents of `L2`,
which is:
```
[3, 4, 5, 3, 4, 5, 3, 4, 5]
```
```python
L1 = [3, 4, 5]
L2 = L1 * 3
print(L1 * 3) # Use an integer instead of 3.0
print(L2)
```
14.B
ANS: Let's analyze the code line by line to identify any errors:
1. **Initialization of `L1`**:
```python
L1 = [3, 3, 8, 1, 3, 0, '1', '0', '2', 'e', 'w', 'e', 'r']
```
- This line is correct. `L1` is initialized as a list containing
a mix of integers and strings.
```python
L1 = [3, 3, 8, 1, 3, 0, '1', '0', '2', 'e', 'w', 'e', 'r']
print(L1[::-1]) # Correctly prints the reversed list
print(L1[-1:-2:-3]) # Correctly prints an empty list
# Corrected version of the third statement:
print(L1[-1:-2:-1]) # This will print the last element in
reverse slicing
```
This way, all statements will run without errors.
1. **Initialization**:
```python
x = ['3', '2', '5']
y = ''
```
- Here, `x` is initialized as a list containing the strings
`'3'`, `'2'`, and `'5'`. The variable `y` is initialized as an
empty string.
2. **While Loop**:
```python
while x:
y = y + x[-1]
x = x[:len(x) - 1]
```
- The loop continues as long as `x` is not empty.
- In each iteration:
- `y = y + x[-1]`: The last element of `x` is added to `y`.
- `x = x[:len(x) - 1]`: The last element is removed from `x`.
Let's go through the iterations:
- **First iteration**:
- `x` is `['3', '2', '5']`
- Last element `'5'` is added to `y`: `y = '5'`
- `x` becomes `['3', '2']`
- **Second iteration**:
- `x` is `['3', '2']`
- Last element `'2'` is added to `y`: `y = '52'`
- `x` becomes `['3']`
- **Third iteration**:
- `x` is `['3']`
- Last element `'3'` is added to `y`: `y = '523'`
- `x` becomes `[]` (empty)
3. **Print Statements**:
```python
print(y)
```
- This prints the value of `y`, which is `'523'`.
```python
print(x)
```
- This prints the value of `x`, which is now an empty list:
`[]`.
```python
print(type(x), type(y))
```
- This prints the types of `x` and `y`:
- `type(x)` will be `<class 'list'>`
- `type(y)` will be `<class 'str'>`
16. Question 16
Complete the code to create a list of every integer between 0 and
100, inclusive, named nums1 using Python, sorted in increasing
order.
ANS: You can create a list of every integer between 0 and 100,
inclusive, using the `range` function in Python. Here's how to do
it:
```python
# Create a list of integers from 0 to 100 inclusive
nums1 = list(range(101))
### Explanation:
- `range(101)` generates a sequence of integers from 0 to 100.
- `list(range(101))` converts that sequence into a list.
- The resulting list `nums1` will be sorted in increasing order by
default, as `range` generates numbers in ascending order.
17. Question 17
Let nums2 and nums3 be two non-empty lists. Write a Python
command that will append the last element of nums3 to the end of
nums2.
ANS: You can append the last element of `nums3` to the end of
`nums2` using the `append()` method in Python. Here's the command
to do that:
```python
nums2.append(nums3[-1])
```
### Explanation:
- `nums3[-1]` accesses the last element of `nums3`.
- `nums2.append()` adds that element to the end of `nums2`.
### Example:
Here’s a complete example for clarity:
```python
nums2 = [1, 2, 3]
nums3 = [4, 5, 6]
# Append the last element of nums3 to nums2
nums2.append(nums3[-1])
18. Consider the following code and predict the result of the following
statements.
bieber = ['om', 'nom', 'nom']
counts = [1, 2, 3]
nums = counts
nums.append(4)
1. counts is nums
2. counts is add([1, 2], [3, 4])
ANS: Let’s analyze the code step by step and predict the results of
the statements:
1. **Initialization**:
```python
bieber = ['om', 'nom', 'nom']
counts = [1, 2, 3]
```
- Here, `bieber` is initialized as a list containing three
strings, and `counts` is initialized as a list containing the
integers `[1, 2, 3]`.
ANS: Let's break down the code step by step to determine the output.
4. **Checking divisibility**:
- The numbers in `numbers` and whether they are divisible by
`3`:
- `0 % 3 == 0` → True, append `0`
- `4 % 3 != 0` → False
- `8 % 3 != 0` → False
- `12 % 3 == 0` → True, append `12`
- `16 % 3 != 0` → False
- `20 % 3 != 0` → False
- `24 % 3 == 0` → True, append `24`
- `28 % 3 != 0` → False
- `32 % 3 != 0` → False
- `36 % 3 == 0` → True, append `36`
- `40 % 3 != 0` → False
- `44 % 3 != 0` → False
- `48 % 3 == 0` → True, append `48`
5. **Final `results`**:
- After the loop, the `results` list will contain:
```
[0, 12, 24, 36, 48]
```
6. **Printing `results`**:
```python
print(results)
```
- This will output:
```
[0, 12, 24, 36, 48]
```
```python
numbers = list(range(0, 51, 4))
results = []
i = 0
### Explanation:
1. **Collecting Results**: The original while loop is used to
append elements (every third element) to the `results` list instead
of printing them directly.
2. **Printing in Reverse**: The `reversed()` function is used to
iterate over the `results` list in reverse order, printing each
number.
### Output:
This modified code will produce the output:
```
48 24 12 0
```
This reflects the reverse of the original output (`0 12 24 36 48`).