- Information
- AI Chat
GE3151 Python Question Bank (2)
python programming (cs8151)
Anna University
Recommended for you
Preview text
Programming GE3151 - PROBLEM SOLVING AND PYTHON PROGRAMMING SYLLABUS UNIT I COMPUTATIONAL THINKING AND PROBLEM SOLVING 9 Fundamentals of Computing – Identification of Computational Problems -Algorithms, building blocks of algorithms ( statements, state, control flow, functions), notation (pseudo code, flow chart, programming language), algorithmic problem solving, simple strategies for developing algorithms (iteration, recursion). Illustrative problems: find minimum in a list, insert a card in a list of sorted cards, guess an integer number in a range, Towers of Hanoi. UNIT II DATA TYPES, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string and list; variables, expressions, statements, tuple assignment, precedence of operators, comments; Illustrative programs: exchange the values of two variables, circulate the values of n variables, distance between two points. UNIT III CONTROL FLOW, FUNCTIONS, STRINGS 9 Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if-elif- else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values, parameters, local and global scope, function composition, recursion; Strings:string slices, immutability, string functions and methods, string module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum an array of numbers, linear search, binary search. UNIT IV LISTS, TUPLES, DICTIONARIES 9 Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods;advanced list processing
- list comprehension; Illustrative programs: simple sorting, histogram, Students marks statement, Retail bill preparation. UNIT V FILES, MODULES, PACKAGES 9 Files and exceptions: text files, reading and writing files, format operator; command line arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs: word count, copy file, Voter’s age validation, Marks range validation (0-100). TOTAL : 45 PERIODS TEXT BOOKS:
- Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition, O’Reilly Publishers, 2016.
- Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and Programming”, 1st Edition, BCS Learning & Development Limited, 2017. REFERENCES:
- Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.
- G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and Data Scientists”, 1st Edition, Notion Press, 2021.
- John V Guttag, "Introduction to Computation and Programming Using Python: With Applications to Computational Modeling and Understanding Data”, Third Edition, MIT Press, 2021
- Eric Matthes, “Python Crash Course, A Hands - on Project Based Introduction to Programming”, 2 nd Edition, No Starch Press, 2019.
- Martin C. Brown, “Python: The Complete Reference”, 4 th Edition, Mc-Graw Hill, 2018.
Programming
UNIT I - ALGORITHMIC PROBLEM SOLVING
PART- A (2 Marks)
What is an algorithm?(Jan-2018,2022) BTL Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for completing a task. It is an English-like representation of the logic which is used to solve the problem. It is a step-by-step procedure for solving a task or a problem. The steps must be ordered, unambiguous and finite in number.
Write an algorithm to find minimum of three numbers. BTL ALGORITHM : Find Minimum of three numbers Step 1: Start Step 2: Read the three numbers A, B, C Step 3: Compare A,B and A,C. If A is minimum, perform step 4 else perform step 5. Step 4:Compare B and C. If B is minimum, output “B is minimum” else output “C is minimum”. Step 5: Stop
List the building blocks of algorithm The building blocks of an algorithm are Statements Sequence Selection or Conditional Repetition or Control flow Functions An action is one or more instructions that the computer performs in sequential order (from first to last). A decision is making a choice among several actions. A loop is one or more instructions that the computer performs repeatedly.
Define statement. List its types The instructions in Python, or indeed in any high-level language, are designed as components for algorithmic problem solving, rather than as one-to-one translations of the underlying machine language instruction set of the computer. Three types of high-level programming language statements. Input/output statements make up one type of statement. An input statement collects a specific value from the user for a variable within the program. An output statement writes a message or the value of a program variable to the user’s screen.
Write the pseudocode to calculate the sum and product of two numbers and display it. BTL INITIALIZE variables sum, product, number1, number2 of type real PRINT “Input two numbers” READ number1, number COMPUTE sum = number1 + number PRINT “The sum is", sum COMPUTE product = number1 * number PRINT “The Product is", product END program
How does flow of control work?BTL Control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. A control flow statement is a statement in which execution results in a choice being made as to which of two or more paths to follow.
Programming
- List the categories of Programming languages
Programming Languages are divided into the following categories: Interpreted Functional Compiled Procedural Scripting Markup Logic-Based Concurrent Object-Oriented Programming Languages. 15. Mention the characteristics of algorithm Algorithm should be precise and unambiguous. Instruction in an algorithm should not be repeated infinitely. Ensure that the algorithm will ultimately terminate. Algorithm should be written in sequence. Algorithm should be written in normal English. Desired result should be obtained only after the algorithm terminates 16. List out the simple strategies to develop an algorithm BTL Algorithm development process consists of five major steps. Step 1: Obtain a description of the problem. Step 2: Analyze the problem. Step 3: Develop a high-level algorithm. Step 4: Refine the algorithm by adding more detail. Step 5: Review the algorithm.
- Compare machine language, assembly language and high-level language. BTL Machine Language Assembly Language High-Level Language
The language of 0s and 1s is called as machine language. The machine language is system independent because there are different set of binary instruction for different types of computer systems
It is low level programming language in which the sequence of 0s and 1s are replaced by mnemonic (ni-monic) codes. Typical instruction for addition and subtraction
High level languages are English like statements and programs. Written in these languages are needed to be translated into machine language before to their execution using a system software compiler. 18. Describe algorithmic problem solving Algorithmic Problem Solving deals with the implementation and application of algorithms to a variety of problems. When solving a problem, choosing the right approach is often the key to arriving at the best solution.
Programming
- Give the difference between recursion and iteration. Jan 2022 BTL Recursion Iteration Function calls itself until the base condition is reached.
Repetition of process until the condition fails.
In recursive function, base case (terminate condition) and recursive case are specified.
Iterative approach involves four steps: initialization, condition, execution and updation. Recursion is slower than iteration due to overhead of maintaining stack.
Iteration is faster.
Recursion takes more memory than iteration due to overhead of maintaining stack.
Iteration takes less memory.
- What are advantages and disadvantages of recursion?BTL Advantages Disadvantages Recursive functions make the code look clean and elegant.
Sometimes the logic behind recursion is hard to follow through. A complex task can be broken down into simpler sub-problems using recursion.
Recursive calls are expensive (inefficient) as they take up a lot of memory and time. Sequence generation is easier with recursion than using some nested iteration.
Recursive functions are hard to debug.
- Write an algorithm to accept two numbers, compute the sum and print the result Step1: Read the two numbers a and b. Step 2: Calculate sum = a+b Step 3: Display the sum Write an algorithm to find the sum of digits of a number and display it Step 1:Start Step 2: Read value of N Step 3: Sum = 0 Step 4: While (N != 0) Rem = N % 10 Sum = Sum + Rem N = N / 10 Step 5: Print Sum Step 6: Stop
- Write an algorithm to find the square and cube and display it Step 1: Start Step 2: Read value of N Step 3: S =NN Step 4: C =SN Step 5: Write values of S,C Step 6: Stop
- Explain Tower of Hanoi. The Tower of Hanoi is a mathematical game. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: Only one disk can be moved at a time. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack. No disk may be placed on top of a smaller disk. With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.
Programming if i > maxNum: maxNum = i print('Maximum Element of the Given List is %d' %(int(maxNum)))
How will you analysis the efficiency of an algorithm? (Nov / Dec 2019) Time efficiency, indicating how fast the algorithm runs. Space efficiency, indicating how much extra memory it uses
How do algorithm, flowchart and pseudo code use for problem solving? (Nov / Dec 2019) Algorithm: A process or set of rules to be followed in calculations or other problem – solving operations, especially by a computer Flowchart: Flowchart is diagrammatic representation of the algorithm. Pseudo code: In Pseudo code normal English language is translated into the programming languages to be worked on. All are tools for problem solving independent of programming language. Difference is only in the way of representing the solution.
PART B (16 MARKS)
- What are the building blocks of an algorithm? Explain in detail.
- Briefly describe iteration and recursion. Explain with algorithm.
- Explain Algorithmic problem solving.
- Write an algorithm and draw a flowchart to calculate 2 4.
- Illustrate Algorithm, Psuedocode and Flowchart with an example.
- a) Describe Psuedocode with its guidelines. b) Give an example for psuedocode. c) Write the pseudocode for Towers of Hanoi.
- a) What is flowchart? b) List down symbols and rules for writing flowchart. c) Draw a flowchart to count and print from1 to 10.
- a) Write a program to find the net salary of an employee. b) Write a program to guess an integer number in a range.
- a) Write a program to insert a card in a list of sorted cards.(Jan-2019) b) Write a program to find the minimum number in a list.
- a) Draw a flow chart to accept three distinct numbers, find the greatest and print the result. (8) (Jan- 2018,Jan-2022) b) Draw a flow chart to find the sum of the series 1+2+3+......+100. (8)(Jan-2018)
- Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem with relevant diagrams. (16) (Jan-2018,Jan2022)
- Identify simple strategies for developing an algorithm. (Jan-2019)
- Mention the different types of iterative structures allowed in python. Explain the use of continue and break statements with an example. (May 2019)
- (a) What is an algorithm? Summarise the characteristics of a good algorithm.(8) (May 2019) (b) Outline the algorithm for displaying the first n odd numbers. (May 2019)
- (a) What is a programming language? What are its types? Explain them in detail with their advantages and disadvantages. (8) (Nov / Dec 2019) (b) Write a function find_index( ), which returns the index of a number in the Fibonacci sequence, if the number is an element of this sequence and returns -1, if the number is not contained in it, call this function using user input and display the result. (8) (Nov / Dec 2019)
- (a) What is recursive function? What are its advantages and disadvantages? Compare it with iterative function. (6) (Nov / Dec 2019) (b) Implement a recursive function in python for the sieve of Eratosthenes. The sieve of Eratosthenes is a simple algorithm for finding all prime numbers up to a specified integer. It was created by the ancient Greek mathematician Eratosthenes. The algorithm to find all the prime numbers less than or equal to a
Programming given integer n: (10) (Nov / Dec 2019) 1) Create a list of integers from two to n: 2,3,4,..., n 2) Start with a counter i set to 2, i. the first prime number 3) Starting from i+1, count up by I and remove those numbers from the list, i. 2i,3i, 4*i,.. 4) Find the first number of the list following i. This is the next prime number. 5) Set i to the number found in the previous step. 6) Repeat steps 3 and 4 until i is greater than n. (As an improvement: It’s enough to go to the square root of n) 7) All the numbers, which are still in the list, are prime numbers. UNIT II – DATA TYPES, EXPRESSIONS, STATEMENTS PART- A (2 Marks)
What is meant by interpreter? An interpreter is a computer program that executes instructions written in a programming language. It can either execute the source code directly or translate the source code in a first step into a more efficient representation and executes this code.
How will you invoke the python interactive interpreter? The Python interpreter can be invoked by typing the command "python" without any parameter followed by the "return" key at the shell prompt.
What are the commands that are used to exit from the python interpreter in UNIX and windows? CTRL+D is used to exit from the python interpreter in UNIX and CTRL+Z is used to exit from the python interpreter in windows.
Define a variable and write down the rules for naming a variable. A name that refers to a value is a variable. Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is good to begin variable names with a lowercase letter.
Write a snippet to display “Hello World” in python interpreter. In script mode: >>>print("Hello World") Hello World In Interactive Mode: >>> "Hello World" 'Hello World'
List down the basic data types in Python. Numbers String List Tuple Dictionary
Define keyword and enumerate some of the keywords in Python. (Jan-2019) A keyword is a reserved word that is used by the compiler to parse a program. Keywords cannot be used as variable names. Some of the keywords used in python are: and del from not while is continue
What do you mean by an operand and an operator? Illustrate your answer with relevant example. An operator is a symbol that specifies an operation to be performed on the operands. The data items that an operator acts upon are called operands. The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and exponentiation.
Programming 19. What do you meant by an assignment statement? An assignment statement creates new variables and gives them values: >>> Message = 'And now for something completely different' >>> n = 17 This example makes two assignments. The first assigns a string to a new variable namedMessage; the second gives the integer 17 to n.
- What is tuple? (or) What is a tuple? How literals of type tuples are written? Give example(Jan-2018) A tuple is a sequence of immutable Python objects. Tuples are sequences, like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated values. Comma- separated values between parentheses can also be used. Example: tup1 = ('physics', 'chemistry', 1997, 2000); tup2= ();
- Define module. A module allows to logically organizing the Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that can bind and reference module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.
- Name the four types of scalar objects Python has. (Jan-2018) int float bool None
- List down the different types of operator. Python language supports the following types of operators: Arithmetic operator Relational operator Assignment operator Logical operator Bitwise operator Membership operator Identity operator
- What is a global variable? Global variables are the one that are defined and declared outside a function and we need to use them inside a function. Example:#This function uses global variable s def f(): print(s)
s = "I love India" f()
- Define function. A function in Python is defined by a def statement. The general syntax looks like this: def function-name(Parameter list): statements # the function body
Programming The parameter list consists of zero or more parameters. Parameters are called arguments, if the function is called. The function body consists of indented statements. The function body gets executed every time the function is called. Parameter can be mandatory or optional. The optional parameters (zero or more) must follow the mandatory parameters. 26. What is the purpose of using comment in python program? Comments indicate information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program. In Python, we use the hash (#) symbol to start writing a comment. Example: #This is a comment 27. State the reasons to divide programs into functions. (Jan-2019) Creating a new function gives the opportunity to name a group of statements, which makes program easier to read and debug. Functions can make a program smaller by eliminating repetitive code. Dividing a long program into functions allows to debug the parts one at a time and then assemble them into a working whole. Well designed functions are often useful for many programs. 28. Outline the logic to swap the content of two identifiers without using third variable. (May 2019) a= b= a=a+b b=a-b a=a-b print(“After Swapping a=”a,” b=”,b)
- State about Logical operators available in python language with example. (May 2019) Logical operators are the and, or, not operators. Operator Meaning Example And True if both the operands are true x and y Or True if either of the operands is true x or y Not True if operand is false (complements the operand) not x
- Compare Interpreter and Compiler (Nov / Dec 2019) Compiler: A Compiler is a program which translates the source code written in a high level language in to object code which is in machine language program. Compiler reads the whole program written in high level language and translates it to machine language. If any error is found, it display error message on the screen. Interpreter: Interpreter translates the high level language program in line by line manner. The interpreter translates a high level language statement in a source program to a machine code and executes it immediately before translating the next statement. When an error is found the execution of the program is halted and error message is displayed on the screen
- Write a python program to circulate the values of n variables (Nov / Dec 2019) no_of_terms = int(input("Enter number of values : ")) list1 = [] for val in range(0,no_of_terms,1): ele = int(input("Enter integer : ")) list1(ele) print("Circulating the elements of list ", list1) for val in range(0,no_of_terms,1): ele = list1(0) list1(ele)
print(list1)
Programming
UNIT III - CONTROL FLOW, FUNCTIONS, STRINGS
PART- A (2 Marks)
- Define Boolean Expression with example. A boolean expression is an expression that is either true or false. The values true and false are called boolean values. The following examples use the operator “==” which compares two operands and produces True if they are equal and False otherwise: Example :>>> 5 == 6 False True and False are special values that belongs to the type bool; they are not strings:
- What are the different types of operators? Arithmetic Operator (+, -, *, /, %, **, // ) Relational operator ( == , !=, <>, < , > , <=, >=) Assignment Operator ( =, += , *= , - =, /=, %= ,**= ) Logical Operator (AND, OR, NOT) Membership Operator (in, not in) Bitwise Operator (& (and), | (or) , ^ (binary Xor), ~(binary 1’s complement , << (binary left shift), >> (binary right shift)) Identity(is, is not)
- Explain modulus operator with example. The modulus operator works on integers and yields the remainder when the first operand is divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the same as for other operators: Example: >>> remainder = 7 % 3 >>> print remainder 1 So 7 divided by 3 is 2 with 1 left over.
- Explain ‘for loop’ with example. for loops are traditionally used when you have a block of code which you want to repeat a fixed number of times. he Python for statement iterates over the members of a sequence in order, executing the block each time. The general form of a for statement is Syntax:
Example:x = 4 for i in range(0, x): print i Output:0 1 2 3 5. Explain relational operators. The == operator is one of the relational operators; the others are: X! = y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y
for variable in sequence: code block
Programming 6. Explain while loop with example.(or)Explain flow of execution of while loop with Example.(Jan 2019) The statements inside the while loop is executed only if the condition is evaluated to true. Syntax:
Example:
Program to add natural numbers upto, sum = 1+2+3+...+n = 10
initialize sum and countersum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter
print the sumprint("The sum is", sum) 7. Explain if-statement and if-else statement with example (or) What are conditional and alternative executions? If statement: The simplest form of if statement is: Syntax:
Example: if x > 0: print 'x is positive' The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens. If-else: A second form of if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this: Example: if x%2 == 0: print 'x is even' else: print 'x is odd' If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. 8. What are chained conditionals? Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional: Eg: if x < y: print 'x is less than y' elif x > y: print 'x is greater than y' else:
if (condition): statement
while condition: statements
Programming 13. Define string immutability. Python strings are immutable. ‘a’ is not a string. It is a variable with string value. You can’t mutate the string but can change what value of the variable to a new string. Program: a = “foo”
Output: #foofoo
a now points to foob=a
b now points to the same foo that a points to#foo It is observed that ‘b’ hasn’t changed even though ‘a’ has changed. a=a+a
a points to the new string “foofoo”, but b points to thesame old “foo” print a print b 14. Explain about string module. The string module contains number of useful constants and classes, as well as some deprecated legacy functions that are also available as methods on strings. Example:
Program: Output: import string upper => MONTY PYTHON'S text = "Monty Python's Flying Circus" FLYING CIRCUS print "upper", "=>", string(text) lower => monty python's flying print "lower", "=>", string(text) circus print "split", "=>", string(text) split => ['Monty', "Python's", print "join", "=>", string(string(text), "+") 'Flying', 'Circus'] print "replace", "=>", string(text, "Python", "Java") join => print "find", "=>", string(text, "Python"), string(text, Monty+Python's+Flying+Circus "Java") replace => Monty Java's Flying print "count", "=>", string(text, "n") Circus find => 6 - count => 3
- Explain global and local scope. (or) Comment with an example on the use of local and global variable with the same identifier name. (May 2019) The scope of a variable refers to the places that you can see or access a variable. If we define a variable on the top of the script or module, the variable is called global variable. The variables that are defined inside a class or function is called local variable. Example: def my_local(): a= print(“This is local variable”) Example: a= def my_global(): print(“This is global variable”)
Programming 16. Compare string and string slices. A string is a sequence of character. Eg: fruit = ‘banana’ String Slices : A segment of a string is called string slice, selecting a slice is similar to selecting a character. Eg:>>> s ='Monty Python' >>> print s[0:5] Monty >>> print s[6:12] Python
Mention a few string functions. s() – Capitalizes first character of string s(sub) – Count number of occurrences of sub in string s() – converts a string to lower case s() – returns a list of words in string
What are string methods? A method is similar to a function. It takes arguments and returns a value. But the syntax is different. For example, the method upper takes a string and returns a new string with all uppercase letters: Instead of the function syntax upper(word), it uses the method syntax word() .>>> word = 'banana' >>> new_word = word() >>> print new_word BANANA
Write a Python program to accept two numbers, multiply them and print the result. (Jan-2018) print(“Enter two numbers”) val1=int(input()) val2=int(input()) prod=val1*val print(“The product of the two numbers is:”,prod)
Write a Python program to accept two numbers, find the greatest and print the result. (Jan-2018) print(“Enter two numbers”) val1=int(input()) val2=int(input()) if (val1>val2): largest=val else: largest=val print(“Largest of two numbers is:”,largest)
What is the purpose of pass statement? Using a pass statement is an explicit way of telling the interpreter to do nothing. Example:def bar(): pass If the function bar() is called, it does absolutely nothing.
Programming b) Write a Python program to perform binary search.(Jan 2019) 13. a) Appraise with an example nested if and elif header in Python (6) (Jan 2018) b) Explain with an example while loop, break statement and continue statement in Python. (10) (Jan 2018,Jan2022) 14. a) Write a Python program to find the factorial of the given number without recursion with recursion.(8)(Jan-2018) b) Write a Python program to generate first ‘N’ Fibonacci series numbers.(Note: Fibonacci numbers are 0, 1,1,2,3,5,8... where each number is the sum of the preceding two).(8) (Jan-2018) 15. (a) If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle. If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. (Nov / Dec 2019) i) Write a function named is_triangle that takes three integers as arguments, and that prints either “yes” or “no”, depending on whether you can or cannot form a triangle from sticks with the given lengths. (4) ii) Write a function that prompts the user to input three stick lengths, converts them to integers, and uses is_triangle to check whether sticks with the given lengths can form a triangle. (4) (b) Write a python program to generate all permutations of a given string using built-in function (8) (Nov / Dec 2019) 16. (a) Compare lists and array with example. Can list be considered as an array? Justify. (6) (Nov / Dec 2019) (b) Write a python function Anagram1( )to check whether two strings are anagram of each other or not with built-in string function and are Anagram2( ) to check the anagram without using built-in string function. (10) (Nov / Dec 2019)
Programming UNIT IV LISTS, TUPLES, DICTIONARIES PART- A (2 Marks)
- What is a list?(Jan-2018) A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except that the elements of a list can have any type.
- Relate String and List? (Jan 2018)(Jan 2019) String: String is a sequence of characters and it is represented within double quotes or single quotes. Strings are immutable. Example: s=”hello” List: A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except that the elements of a list can have any type and it is mutable. Example: b= [’a’, ’b’, ’c’, ’d’, 1, 3]
- Solve a)[0] * 4 and b) [1, 2, 3] * 3. >>> [0] * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
- Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:]. >>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’] >>> list[1:3] [’b’, ’c’] >>> list[:4] [’a’, ’b’, ’c’, ’d’] >>> list[3:] [’d’, ’e’, ’f’]
- Mention any 5 list methods. append() extend () sort() pop() index() insert remove()
- State the difference between lists and dictionary. Lists Dictionary List is a mutable type meaning that it can be modified. List can store a sequence of objects in a certain order. Example: list1=[1,’a’,’apple’]
Dictionary is immutable and is a key value store. Dictionary is not ordered and it requires that the keys are hashable. Example: dict1={‘a’:1, ‘b’:2}
GE3151 Python Question Bank (2)
Course: python programming (cs8151)
University: Anna University
- Discover more from: