Having trouble with lists :( | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Having trouble with lists :(

I want to write a code where I will define a function which can do operation on a list. But I don’t understand how to do it. Like similar code with string type variable:- def add(x): x*=2 x+=1 print (x) z=5 add(z) Now instead of a string type variable z, I want to apply this on a list. Anybody help please :( (I personally not understanding a lot of things about list.can anybody suggest some good study material for lists? Or any advise.)

31st May 2020, 4:52 PM
Mir Abir Hossain
Mir Abir Hossain - avatar
7 Answers
+ 6
Mir Abir Hossain, i am still not sure what you are going to do. The function seems clear, but what do you mean by " ... want to apply this on a list" . Please be so kind and add some more information to your task description. define a list and describe what the result of the function should be done with the list. append? replace? Show the list before the action and after the action. The more information we have and the better the samples are, the faster we can help. Thanks!
31st May 2020, 6:02 PM
Lothar
Lothar - avatar
+ 4
If you want to do operation with each value in list you may try map() function. Example:- List = [1,2,3,4] list(map(lambda x : x*2 +1,List))) #It will give [3,5,7,9] Thank You ☺️
31st May 2020, 5:03 PM
Hacker Badshah
Hacker Badshah - avatar
+ 3
Thank you Hacker Badshah Mahinder $ingh rodwynnejones and Abhay.
31st May 2020, 5:11 PM
Mir Abir Hossain
Mir Abir Hossain - avatar
+ 2
I Don't have any advice or good material to suggest but here is a simple list operation def add(x,y): c=x+y return c List1=[1,2,3] List2=[4,5,6] print(add(List1,List2)) Prints [1,2,3,4,5,6]
31st May 2020, 4:56 PM
Abhay
Abhay - avatar
+ 2
Thank you Lothar. I was trying to writr this code where I can add two or more list by defining a function. Finally I am able to do this. a=[1,3,5,7] b=[9,11,13] def fn(x,y): if type(x)==list: x.extend(y) fn(a,b) print (a) I couldn’t make the if statement earlier. also didn’t know the extend method. Thanks everyone. :)
31st May 2020, 11:09 PM
Mir Abir Hossain
Mir Abir Hossain - avatar
31st May 2020, 5:04 PM
Maninder $ingh
Maninder $ingh - avatar
+ 1
for num in [1, 2, 3, 4, 5, 6]: add(num)
31st May 2020, 5:05 PM
rodwynnejones
rodwynnejones - avatar