Python Programming - Variables

Exercise : Variables - General Questions
  • Variables - General Questions
11.
What is the value of x after executing the following code:
x = [1, 2, 3]
y = x
x[0] = 4
print(y)
[4, 2, 3]
[1, 2, 3]
[4, 2, 2]
An error is raised
Answer: Option
Explanation:
In Python, when a list is assigned to a variable, the variable holds a reference to the list rather than a copy of the list. In this case, the variable y holds a reference to the same list as x. When x[0] is changed to 4, the list is modified and both x and y reflect this change.

12.
Which of the following is a valid way to create an empty list?
my_list = []
my_list = lst()
my_list = {}
All of the above
Answer: Option
Explanation:

In Python, you can create an empty list using the following ways:

# Using square brackets:
my_list = []

#Using the list() constructor:
my_list = list()

Both of these methods will create an empty list in Python.


13.
What is the difference between a global variable and a local variable?
Global variables have a shorter lifespan than local variables.
Global variables can only be accessed within a specific function, while local variables can be accessed anywhere in the code.
Global variables can be accessed anywhere in the code, while local variables can only be accessed within a specific function.
There is no difference between a global variable and a local variable.
Answer: Option
Explanation:

In Python, a global variable is a variable that is defined outside of any function and can be accessed from anywhere in the code. A local variable, on the other hand, is a variable that is defined within a function and can only be accessed within that function.

Global variables exist throughout the entire program's execution, while local variables are created when a function is called and are destroyed when the function completes. Therefore, global variables have a longer lifespan than local variables.


14.
Which of the following is a valid way to access the last item in a list called my_list?
my_list.last
my_list[-1]
my_list[0]
my_list[len(my_list)]
Answer: Option
Explanation:
In Python, negative indices can be used to access elements from the end of a list. An index of -1 refers to the last item in the list, -2 refers to the second-to-last item, and so on. So my_list[-1] would access the last item in the list.

15.
What is the value of x after executing the following code:
x = 10
x += 5
x *= 2
print(x)
15
25
30
125
Answer: Option
Explanation:

In Python, the += operator is used to add a value to a variable, and the *= operator is used to multiply a variable by a value.

In this case, x starts at 10, then 5 is added to it to make it 15, and then it is multiplied by 2 to make it 30.

The final value of x is 30.