Question #105231

Provide your own examples of the following using Python lists. Create your own examples. Do not copy them from another source.


Nested lists

The “*” operator

List slices

The “+=” operator

A list filter

A list operation that is legal but does the "wrong" thing, not what the programmer expects

Provide the Python code and output for your program and all your examples.

Expert's answer

Nested lists:

list_one = [[ 1, 2, 3, 4] , [ "H", "u", "n", "t", "e", "r"] , [ 23, 34, 11]]


The “*” operator:

def func (*x):

   return   list(x)

print(func(7,5,3)) #[7, 5, 3]


list_one = [ 1, 2, 3, 4]

print(list_one*2) #[1, 2, 3, 4, 1, 2, 3, 4]


List slices:

list_one = [ 1, 5 ,6, 7, 9]

list_two = list_one[1:4] #[5, 6, 7]


The “+=” operator:

list_one = [ 1, 5 ,6, 7, 9]

for i in list_one:

   i += 1

   print(i, end = " ") #2 6 7 8 10


A list filter :

list_one = [ 1, 5 ,6, 7, 9]

list_two = filter(lambda x: x % 2 == 0, list_one)

print(list(list_two)) #[6]


A list operation that is legal but does the "wrong" thing, not what the programmer expects:

def func(x, list_one=[]):

   list_one.append(x)

   print (list_one)


func(3)

func(4)

func(5) #we expect [3][4][5] 


#but have

[3] [3, 4] [3, 4, 5


LATEST TUTORIALS
APPROVED BY CLIENTS