Incorrect declaration of list in python

Python lists are one of the most versatile data types that allow us to work with multiple elements at once. For example,

# a list of programming languages ['Python', 'C++', 'JavaScript']

Create Python Lists

In Python, a list is created by placing elements inside square brackets [], separated by commas.

# list of integers my_list = [1, 2, 3]

A list can have any number of items and they may be of different types (integer, float, string, etc.).

# empty list my_list = [] # list with mixed data types my_list = [1, "Hello", 3.4]

A list can also have another list as an item. This is called a nested list.

# nested list my_list = ["mouse", [8, 4, 6], ['a']]

Access List Elements

There are various ways in which we can access the elements of a list.

List Index

We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.

Trying to access indexes other than these will raise an IndexError. The index must be an integer. We can't use float or other types, this will result in TypeError.

Nested lists are accessed using nested indexing.

my_list = ['p', 'r', 'o', 'b', 'e'] # first item print(my_list[0]) # p # third item print(my_list[2]) # o # fifth item print(my_list[4]) # e # Nested List n_list = ["Happy", [2, 0, 1, 5]] # Nested indexing print(n_list[0][1]) print(n_list[1][3]) # Error! Only integer can be used for indexing print(my_list[4.0])

Output

p o e a 5 Traceback (most recent call last): File "<string>", line 21, in <module> TypeError: list indices must be integers or slices, not float

Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

# Negative indexing in lists my_list = ['p','r','o','b','e'] # last item print(my_list[-1]) # fifth last item print(my_list[-5])

Output

e p
Incorrect declaration of list in python
List indexing in Python

List Slicing in Python

We can access a range of items in a list by using the slicing operator :.

# List slicing in Python my_list = ['p','r','o','g','r','a','m','i','z'] # elements from index 2 to index 4 print(my_list[2:5]) # elements from index 5 to end print(my_list[5:]) # elements beginning to end print(my_list[:])

Output

['o', 'g', 'r'] ['a', 'm', 'i', 'z'] ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

Note: When we slice lists, the start index is inclusive but the end index is exclusive. For example, my_list[2: 5] returns a list with elements at index 2, 3 and 4, but not 5.

Add/Change List Elements

Lists are mutable, meaning their elements can be changed unlike string or tuple.

We can use the assignment operator = to change an item or a range of items.

# Correcting mistake values in a list odd = [2, 4, 6, 8] # change the 1st item odd[0] = 1 print(odd) # change 2nd to 4th items odd[1:4] = [3, 5, 7] print(odd)

Output

[1, 4, 6, 8] [1, 3, 5, 7]

We can add one item to a list using the append() method or add several items using the extend() method.

# Appending and Extending lists in Python odd = [1, 3, 5] odd.append(7) print(odd) odd.extend([9, 11, 13]) print(odd)

Output

[1, 3, 5, 7] [1, 3, 5, 7, 9, 11, 13]

We can also use + operator to combine two lists. This is also called concatenation.

The * operator repeats a list for the given number of times.

# Concatenating and repeating lists odd = [1, 3, 5] print(odd + [9, 7, 5]) print(["re"] * 3)

Output

[1, 3, 5, 9, 7, 5] ['re', 're', 're']

Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.

# Demonstration of list insert() method odd = [1, 9] odd.insert(1,3) print(odd) odd[2:2] = [5, 7] print(odd)

Output

[1, 3, 9] [1, 3, 5, 7, 9]

Delete List Elements

We can delete one or more items from a list using the Python del statement. It can even delete the list entirely.

# Deleting list items my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] # delete one item del my_list[2] print(my_list) # delete multiple items del my_list[1:5] print(my_list) # delete the entire list del my_list # Error: List not defined print(my_list)

Output

['p', 'r', 'b', 'l', 'e', 'm'] ['p', 'm'] Traceback (most recent call last): File "<string>", line 18, in <module> NameError: name 'my_list' is not defined

We can use remove() to remove the given item or pop() to remove an item at the given index.

The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure).

And, if we have to empty the whole list, we can use the clear() method.

my_list = ['p','r','o','b','l','e','m'] my_list.remove('p') # Output: ['r', 'o', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'o' print(my_list.pop(1)) # Output: ['r', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'm' print(my_list.pop()) # Output: ['r', 'b', 'l', 'e'] print(my_list) my_list.clear() # Output: [] print(my_list)

Output

['r', 'o', 'b', 'l', 'e', 'm'] o ['r', 'b', 'l', 'e', 'm'] m ['r', 'b', 'l', 'e'] []

Finally, we can also delete items in a list by assigning an empty list to a slice of elements.

>>> my_list = ['p','r','o','b','l','e','m'] >>> my_list[2:3] = [] >>> my_list ['p', 'r', 'b', 'l', 'e', 'm'] >>> my_list[2:5] = [] >>> my_list ['p', 'r', 'm']

Python List Methods

Python has many useful list methods that makes it really easy to work with lists. Here are some of the commonly used list methods.

Methods Descriptions
append() adds an element to the end of the list
extend() adds all elements of a list to another list
insert() inserts an item at the defined index
remove() removes an item from the list
pop() returns and removes an element at the given index
clear() removes all items from the list
index() returns the index of the first matched item
count() returns the count of the number of items passed as an argument
sort() sort items in a list in ascending order
reverse() reverse the order of items in the list
copy() returns a shallow copy of the list

# Example on Python list methods my_list = [3, 8, 1, 6, 8, 8, 4] # Add 'a' to the end my_list.append('a') # Output: [3, 8, 1, 6, 8, 8, 4, 'a'] print(my_list) # Index of first occurrence of 8 print(my_list.index(8)) # Output: 1 # Count of 8 in the list print(my_list.count(8)) # Output: 3

List Comprehension: Elegant way to create Lists

List comprehension is an elegant and concise way to create a new list from an existing list in Python.

A list comprehension consists of an expression followed by for statement inside square brackets.

Here is an example to make a list with each item being increasing power of 2.

pow2 = [2 ** x for x in range(10)] print(pow2)

Output

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

This code is equivalent to:

pow2 = [] for x in range(10): pow2.append(2 ** x)

A list comprehension can optionally contain more for or if statements. An optional if statement can filter out items for the new list. Here are some examples.

>>> pow2 = [2 ** x for x in range(10) if x > 5] >>> pow2 [64, 128, 256, 512] >>> odd = [x for x in range(20) if x % 2 == 1] >>> odd [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] >>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']] ['Python Language', 'Python Programming', 'C Language', 'C Programming']

Visit Python list comprehension to learn more.

Other List Operations in Python

List Membership Test

We can test if an item exists in a list or not, using the keyword in.

my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] # Output: True print('p' in my_list) # Output: False print('a' in my_list) # Output: True print('c' not in my_list)

Output

True False True

Iterating Through a List

Using a for loop we can iterate through each item in a list.

for fruit in ['apple','banana','mango']: print("I like",fruit)

Output

I like apple I like banana I like mango

1) What is the maximum possible length of an identifier?

  1. 16
  2. 32
  3. 64
  4. None of these above

Answer: (d) None of these above

Explanation: The maximum possible length of an identifier is not defined in the python language. It can be of any number.

2) Who developed the Python language?

  1. Zim Den
  2. Guido van Rossum
  3. Niene Stom
  4. Wick van Rossum

Answer: (b) Guido van Rossum

Explanation: Python language was developed by Guido van Rossum in the Netherlands.

3) In which year was the Python language developed?

Answer: (d) 1989

Explanation: Python language was developed by Guido van Rossum in 1989.

4) In which language is Python written?

  1. English
  2. PHP
  3. C
  4. All of the above

Answer: (b) C

Explanation: Python is written in C programming language, and it is also called CPython.

5) Which one of the following is the correct extension of the Python file?

  1. .py
  2. .python
  3. .p
  4. None of these

Answer: (a) .py

Explanation: ".py" is the correct extension of the Python file.

6) In which year was the Python 3.0 version developed?

Answer: (a) 2008

Explanation: Python 3.0 version was developed on December 3, 2008.

7) What do we use to define a block of code in Python language?

  1. Key
  2. Brackets
  3. Indentation
  4. None of these

Answer: (c) Indentation

Explanation: Python uses indentation to define blocks of code. Indentations are simply spaces or tabs used as an indicator that is part of the indent code child. As used in curly braces C, C++, and Java.

8) Which character is used in Python to make a single line comment?

Answer: (c) #

Explanation: "#" character is used in Python to make a single-line comment.

9) Which of the following statements is correct regarding the object-oriented programming concept in Python?

  1. Classes are real-world entities while objects are not real
  2. Objects are real-world entities while classes are not real
  3. Both objects and classes are real-world entities
  4. All of the above

Answer: (b) Objects are real-world entities while classes are not real

Explanation: None

10) Which of the following statements is correct in this python code?

class Name: def __init__(javatpoint): javatpoint = java name1=Name("ABC") name2=name1

  1. It will throw the error as multiple references to the same object is not possible
  2. id(name1) and id(name2) will have same value
  3. Both name1 and name2 will have reference to two different objects of class Name
  4. All of the above

Answer: (b) id(name1) and id(name2) will have same value

Explanation: "name1" and "name2" refer to the same object, so id(name1) and id(name2) will have the same value.

11) What is the method inside the class in python language?

  1. Object
  2. Function
  3. Attribute
  4. Argument

Answer: (b) Function

Explanation: Function is also known as the method.

12) Which of the following declarations is incorrect?

  1. _x = 2
  2. __x = 3
  3. __xyz__ = 5
  4. None of these

Answer: (d) None of these

Explanation: All declarations will execute successfully but at the expense of low readability.

13) Why does the name of local variables start with an underscore discouraged?

  1. To identify the variable
  2. It confuses the interpreter
  3. It indicates a private variable of a class
  4. None of these

Answer: (c) It indicates a private variable of a class

Explanation: Since there is no concept of private variables in Python language, the major underscore is used to denote variables that cannot be accessed from outside the class.

14) Which of the following is not a keyword in Python language?

Answer: (a) val

Explanation: "val" is not a keyword in python language.

15) Which of the following statements is correct for variable names in Python language?

  1. All variable names must begin with an underscore.
  2. Unlimited length
  3. The variable name length is a maximum of 2.
  4. All of the above

Answer: (b) Unlimited length

Explanation: None

16) Which of the following declarations is incorrect in python language?

  1. xyzp = 5,000,000
  2. x y z p = 5000 6000 7000 8000
  3. x,y,z,p = 5000, 6000, 7000, 8000
  4. x_y_z_p = 5,000,000

Answer: (b) x y z p = 5000 6000 7000 8000

Explanation: Spaces are not allowed in variable names.

17) Which of the following words cannot be a variable in python language?

Answer: (c) try

Explanation: "try" is a keyword.

18) Which of the following operators is the correct option for power(ab)?

  1. a ^ b
  2. a**b
  3. a ^ ^ b
  4. a ^ * b

Answer: (b) a**b

Explanation: The power operator in python is a**b, i.e., 2**3=8.

19) Which of the following precedence order is correct in Python?

  1. Parentheses, Exponential, Multiplication, Division, Addition, Subtraction
  2. Multiplication, Division, Addition, Subtraction, Parentheses, Exponential
  3. Division, Multiplication, Addition, Subtraction, Parentheses, Exponential
  4. Exponential, Parentheses, Multiplication, Division, Addition, Subtraction

Answer: (a) Parentheses, Exponential, Multiplication, Division, Addition, Subtraction

Explanation: PEMDAS (similar to BODMAS).

20) Which one of the following has the same precedence level?

  1. Division, Power, Multiplication, Addition and Subtraction
  2. Division and Multiplication
  3. Subtraction and Division
  4. Power and Division

Answer: (b) Division and Multiplication

Explanation: None

21) Which one of the following has the highest precedence in the expression?

  1. Division
  2. Subtraction
  3. Power
  4. Parentheses

Answer: (d) Parentheses

Explanation: PEMDAS (similar to BODMAS).

22) Which of the following functions is a built-in function in python language?

  1. val()
  2. print()
  3. print()
  4. None of these

Answer: (b) print()

Explanation: The print() function is a built-in function in python language that prints a value directly to the system.

23) Study the following function:

round(4.576)

What will be the output of this function?

Answer: (d) 5

Explanation: The round function is a built-in function in the Python language that round-off the value (like 3.85 is 4), so the output of this function will be 5.

24) Which of the following is correctly evaluated for this function?

pow(x,y,z)

  1. (x**y) / z
  2. (x / y) * z
  3. (x**y) % z
  4. (x / y) / z

Answer: (c) (x**y) % z

Explanation: None

25) Study the following function:

all([2,4,0,6])

What will be the output of this function?

  1. False
  2. True
  3. 0
  4. Invalid code

Answer: (a) False

Explanation: If any element is zero, it returns a false value, and if all elements are non-zero, it returns a true value. Hence, the output of this "all([2,4,0,6])" function will be false.

26) Study the following program:

x = 1 while True: if x % 5 = = 0: break print(x) x + = 1

What will be the output of this code?

  1. error
  2. 2 1
  3. 0 3 1
  4. None of these

Answer: (a) error

Explanation: Syntax error, there should not be a space between + and =.

27) Which one of the following syntaxes is the correct syntax to read from a simple text file stored in ''d:\java.txt''?

  1. Infile = open(''d:\\java.txt'', ''r'')
  2. Infile = open(file=''d:\\\java.txt'', ''r'')
  3. Infile = open(''d:\java.txt'',''r'')
  4. Infile = open.file(''d:\\java.txt'',''r'')

Answer: (a) Infile = open(''c:\\scores.txt'', ''r'')

Explanation: None

28) Study the following code:

x = ['XX', 'YY'] for i in a: i.lower() print(a)

What will be the output of this program?

  1. ['XX', 'YY']
  2. ['xx', 'yy']
  3. [XX, yy]
  4. None of these

Answer: (a) ['XX', 'YY']

Explanation: None

29) Study the following function:

import math abs(math.sqrt(36))

What will be the output of this code?

Answer: (d) 6.0

Explanation: This function prints the square of the value.

30) Study the following function:

any([5>8, 6>3, 3>1])

What will be the output of this code?

  1. False
  2. Ture
  3. Invalid code
  4. None of these

Answer: (b) True

Explanation: None

31) Study the following statement:

>>>"a"+"bc"

What will be the output of this statement?

Answer: (b) abc

Explanation: In Python, the "+" operator acts as a concatenation operator between two strings.

32) Study the following code:

>>>"javatpoint"[5:]

What will be the output of this code?

  1. javatpoint
  2. java
  3. point
  4. None of these

Answer: (c) point

Explanation: Slice operation is performed on the string.

33) The output to execute string.ascii_letters can also be obtained from:?

  1. character
  2. ascii_lowercase_string.digits
  3. lowercase_string.upercase
  4. ascii_lowercase+string.ascii_upercase

Answer: (d) string.ascii_lowercase+string.ascii_upercase

Explanation: None

34) Study the following statements:

>>> str1 = "javat" >>> str2 = ":" >>> str3 = "point" >>> str1[-1:]

What will be the output of this statement?

Answer: (a) t

Explanation: The correct output of this program is "t" because -1 corresponds to the last index.

35) Study the following code:

>>> print (r"\njavat\npoint")

What will be the output of this statement?

  1. java
    point
  2. java point
  3. \njavat\npoint
  4. Print the letter r and then javat and then point

Answer: (c) \njavat\npoint

Explanation: None

36) Study the following statements:

>>> print(0xA + 0xB + 0xC)

What will be the output of this statement?

  1. 33
  2. 63
  3. 0xA + 0xB + 0xC
  4. None of these

Answer: (a) 33

Explanation: A, B and C are hexadecimal integers with values 10, 11 and 12 respectively, so the sum of A, B and C is 33.

37) Study the following program:

class book: def __init__(a, b): a.o1 = b class child(book): def __init__(a, b): a.o2 = b obj = page(32) print "%d %d" % (obj.o1, obj.o2)

Which of the following is the correct output of this program?

  1. 32
  2. 32 32
  3. 32 None
  4. Error is generated

Answer: (d) Error is generated

Explanation: Error is generated because self.o1 was never created.

38) Study the following program:

class Std_Name: def __init__(self, Std_firstName, Std_Phn, Std_lastName): self.Std_firstName = Std_firstName self. Std_Phn = Std_Phn self. Std_lastName = Std_lastName Std_firstName = "Wick" name = Std_Name(Std_firstName, 'F', "Bob") Std_firstName = "Ann" name.lastName = "Nick" print(name.Std_firstName, name.Std_lastName)

What will be the output of this statement?

  1. Ann Bob
  2. Ann Nick
  3. Wick Bob
  4. Wick Nick

Answer: (d) Wick Nick

Explanation: None

39) Study the following statements:

>>> print(ord('h') - ord('z'))

What will be the output of this statement?

Answer: (b) -18

Explanation: ASCII value of h is less than the z. Hence the output of this code is 104-122, which is equal to -18.

40) Study the following program:

x = ['xy', 'yz'] for i in a: i.upper() print(a)

Which of the following is correct output of this program?

  1. ['xy', 'yz']
  2. ['XY', 'YZ']
  3. [None, None]
  4. None of these

Answer: (a) ['xy', 'yz']

Explanation: None

41) Study the following program:

i = 1: while True: if i%3 == 0: break print(i)

Which of the following is the correct output of this program?

  1. 1 2 3
  2. 3 2 1
  3. 1 2
  4. Invalid syntax

Answer: (d) Invalid syntax

Explanation: Invalid syntax, because this declaration (i = 1:) is wrong.

42) Study the following program:

a = 1 while True: if a % 7 = = 0: break print(a) a += 1

Which of the following is correct output of this program?

  1. 1 2 3 4 5
  2. 1 2 3 4 5 6
  3. 1 2 3 4 5 6 7
  4. Invalid syntax

Answer: (b) 1 2 3 4 5 6

Explanation: None

43) Study the following program:

i = 0 while i < 5: print(i) i += 1 if i == 3: break else: print(0)

What will be the output of this statement?

  1. 1 2 3
  2. 0 1 2 3
  3. 0 1 2
  4. 3 2 1

Answer: (c) 0 1 2

Explanation: None

44) Study the following program:

i = 0 while i < 3: print(i) i += 1 else: print(0)

What will be the output of this statement?

  1. 0 1
  2. 0 1 2
  3. 0 1 2 0
  4. 0 1 2 3

Answer: (c) 0 1 2 0

Explanation: None

45) Study the following program:

z = "xyz" j = "j" while j in z: print(j, end=" ")

What will be the output of this statement?

  1. xyz
  2. No output
  3. x y z
  4. j j j j j j j..

Answer: (b) No output

Explanation: "j" is not in "xyz".

46) Study the following program:

x = 'pqrs' for i in range(len(x)): x[i].upper() print (x)

Which of the following is the correct output of this program?

  1. PQRS
  2. pqrs
  3. qrs
  4. None of these

Answer: (b) pqrs

Explanation: None

47) Study the following program:

d = {0: 'a', 1: 'b', 2: 'c'} for i in d: print(i)

What will be the output of this statement?

  1. a b c
  2. 0 1 2
  3. 0 a   1 b   2 c
  4. None of these above

Answer: (b) 0 1 2

Explanation: None

48) Study the following program:

d = {0, 1, 2} for x in d: print(x)

What will be the output of this statement?

  1. {0, 1, 2} {0, 1, 2} {0, 1, 2}
  2. 0 1 2
  3. Syntax_Error
  4. None of these above

Answer: (b) 0 1 2

Explanation: None

49) Which of the following option is not a core data type in the python language?

  1. Dictionary
  2. Lists
  3. Class
  4. All of the above

Answer: (c) Class

Explanation: Class is not a core data type because it is a user-defined data type.

50) What error will occur when you execute the following code?

MANGO = APPLE

  1. NameError
  2. SyntaxError
  3. TypeError
  4. ValueError

Answer: (a) NamaError

Explanation: Mango is not defined hence the name error.

51) Study the following program:

def example(a): a = a + '1' a = a*1 return a >>>example("javatpoint")

What will be the output of this statement?

  1. hello2hello2
  2. hello2
  3. Cannot perform mathematical operation on strings
  4. indentationError

Answer: (d) indentationError

Explanation: None

52) Which of the following data types is shown below?

L = [2, 54, 'javatpoint', 5]

What will be the output of this statement?

  1. Dictionary
  2. Tuple
  3. List
  4. Stack

Answer: (c) List

Explanation: Any value can be stored in the list data type.

53) What happens when '2' == 2 is executed?

  1. False
  2. Ture
  3. ValueError occurs
  4. TypeError occurs

Answer: (a) False

Explanation: It only evaluates to false.

54) Study the following program:

try: if '2' != 2: raise "JavaTpoint" else: print("JavaTpoint has not exist") except "JavaTpoint": print ("JavaTpoint has exist")

What will be the output of this statement?

  1. invalid code
  2. JavaTpoint has not exist
  3. JavaTpoint has exist
  4. none of these above

Answer: (a) invalid code

Explanation: A new exception class must inherit from a BaseException, and there is no such inheritance here.

55) Study the following statement

z = {"x":0, "y":1}

Which of the following is the correct statement?

  1. x dictionary z is created
  2. x and y are the keys of dictionary z
  3. 0 and 1 are the values of dictionary z
  4. All of the above

Answer: (d) All of the above

Explanation: All of the above statements is correct regarding Python code.

Next TopicPython MCQ Part 2