Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform an action on each element of a list and put the results in a new list in Python?

Tags:

python

loops

list

Hey I'm having a problem trying to figure this out:

Lets start out with a list with elements and a blank list.

L = [a, b, c]  
BL = [  ]

What I need to do is perform a task on L[0] and have the result put into BL[0]. Then perform a task on L[1] and have the result put into BL [1]. And then of course the same with the last element in the list. Resulting in

L = [a, b, c]
BL =[newa, newb, newc]

I hope you understand what I'm trying to figure out. I'm new to programming and I'm guessing this is probably done with a for loop but I keep getting errors.

Ok SO I here's the what I tried. Note: links is a list of links.

def blah(links):
   html = [urlopen( links ).read() for link in links]
   print html[1]

and I get this error:

Traceback (most recent call last):
File "scraper.py", line 60, in <module>
main()
File "scraper.py", line 51, in main
getmail(links)
File "scraper.py", line 34, in getmail
html = [urlopen( links ).read() for link in links]
File "/usr/lib/python2.6/urllib.py", line 86, in urlopen
return opener.open(url)
File "/usr/lib/python2.6/urllib.py", line 177, in open
fullurl = unwrap(toBytes(fullurl))
File "/usr/lib/python2.6/urllib.py", line 1032, in unwrap
url = url.strip()
AttributeError: 'list' object has no attribute 'strip'
like image 965
moretimetocry Avatar asked Dec 09 '22 21:12

moretimetocry


1 Answers

Simple, do this:

BL = [function(x) for x in L]
like image 184
SexyBeast Avatar answered Dec 11 '22 10:12

SexyBeast