How would you access the last element of a list stored in a variable named my_list?
- my_list[-1]
- my_list[0]
- my_list[1]
- my_list[len(my_list)]
In Python, my_list[-1] is used to access the last element of a list. my_list[0] would access the first element. my_list[1] would access the second element. my_list[len(my_list)] would cause an IndexError as the index would be out of range.
What would be the output of the following Python code? print(type([]))
- <class 'str'>
- <class 'list'>
- <class 'int'>
- <class 'tuple'>
The output of type([]) would be <class 'list'> because the empty square brackets [] represent an empty list, so the type() function returns <class 'list'>.
How to create a single string without separators from a list of multiple strings?
- ''.join(my_list)
- ', '.join(my_list)
- ' '.join(my_list)
- '-'.join(my_list)
To create a single string from a list of multiple strings, you can use any of the options depending on the separator you want between the strings. Here’s a breakdown:
''.join(my_list) – This joins the list items into a single string with no separator between them.
', '.join(my_list) – This joins the list items into a single string with a comma and a space as separators.
' '.join(my_list) – This joins the list items into a single string with a space as the separator.
'-'.join(my_list) – This joins the list items into a single string with a hyphen as the separator.
Which Python built-in function would you use to convert a string into a number?
list()int()str()float()int()orfloat()
To convert a string into a number in Python, you can use the built-in functions int() or float(), depending on whether you want an integer or a floating-point number. The int() function is used to convert a string into an integer, while float() is used to convert a string into a float number. str() converts other data types to string and list() converts other types to list.