📖 generic · 12th TN - English Medium · COMPUTER SCIENCE · Page 138question

LISTS, TUPLES, SETS AND DICTIONARY · Part 8

Chapter 3: 4 · COMPUTER SCIENCE

the result of range() as a list. Syntax: = list ( range ( ) ) The list ( ) function is also used to create list in python. Note 12th Computer Chapter - - >>> = list(range( , , )) >>> print( ) [ , , , , ] Example In the above code, list() function takes the result of range() as elements. Thus, list has the elements of first five even numbers.

Similarly, we can create any series of values using range() function. The following example explains how to create a list with squares of first natural numbers. squares = [ ] for x in range( , ): s = x ** squares.append(s) print (squares) Example : Generating squares of first natural numbers In the above program, an empty list is created named “squares”. Then, the for loop generates natural numbers from to using range() function.

Inside the loop, the current value of x is raised to the power and stored in the variables. Each new value of square is appended to the list “squares”. Finally, the program shows the following values as output. Output [ , , , , , , , , , ] .

. List comprehensions List comprehension is a simplest way of creating sequence of elements that satisfy a certain condition. Syntax: List = [ expression for variable in range ] >>> squares = [ x ** for x in range( , ) ] >>> print (squares) Output: [ , , , , , , , , , ] Example : Generating squares of first natural numbers using the concept of List comprehension 12th Computer Chapter - - Lists, Tuples, Sets and Dictionary In the above example, x ** in the expression is evaluated each time it is iterated. This is the shortcut method of generating series of values.

. . Other important list funcion Function Description Syntax Example copy ( ) Returns a copy of the list List.copy( ) MyList=[ , , ] x = MyList.copy() print(x) Output: [ , , ] count ( ) Returns the

Related topics

Have a question about this topic?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →