How can I do this with list comprehension? Or how can I extract every even position element from list and store it in a list? - python-3.x

p = [i.text.strip() for i in soup.select('p.card-text')]
j = []
for i in p:
if p.index(i)%2 == 0:
j.append(i)
I am doing this because I only want to extract even position element from my list p.
Is there any other way to do this (to get only even position element from list)?
If not, how can I write the code above using list comprehension? I have extracted even position element using this code. I want to know of any other method I can apply or how to write list comprehension for the above code?

You can try the following by using list comprehension along with enumerate in python
p = [i.text.strip() for index,i in enumerate(soup.select('p.card-text')) if index%2==0]

Um... simply slice:
j = p[::2]
Or if select returns a list (looks like it does), do it earlier to save work:
soup.select('p.card-text')[::2]

Related

Appending Elements From Left/Start of List/Array

I came across appending elements to array from left. and it has two solution
Solution 1:
List = [2,3,4,5,6]
List.insert(0,1) # Using insert
List = [1,2,3,4,5,6]
Solution 2:
List = [2,3,4,5,6]
[1] + List # Concatenation of array
List = [1,2,3,4,5,6]
I'm new to Python So please can any one explain the time complexity of both solution according to me both solution takes O(n) am I right or wrong?

How a Python code to store integer in list and then find the sum of integer stored in the List

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list
lst = list( input("Enter the list of items :") )
sum_element = 0
for i in lst:
sum_element = sum_element+int(i)
print(sum_element)
Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].
list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].
So to get the input list you might want to do something like this:
my_list = []
for i in range(int(input('Length: '))):
my_list.append(int(input(f'Element {i}: ')))
and then continue with your code for summation.
A more pythonic way would be
my_list = [int(input(f'Element {i}: '))
for i in range(int(input('Length: ')))]
For adding all the elements up you could use the inbuilt sum() function:
my_list_sum = sum(my_list)
lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

How to Change position of elements in python list

I have a python list like
the_list= ['john',"nick","edward","mood","enp","wick"]
i always want the mood and enp to be in the 0th and 1st index of list rest order can be anything.
so the output will be
op_list= ["mood","enp",........rest..]
The following will work:
op_list = ["mood", "enp"] + [x for x in the_list if x not in ("mood", "enp")]
This assumes the two special elements are always present.

Python 3: Add string to OBJECTS within a list

I am sure it is a very trivial question but I can not seem to find anything online, perhaps because I am not using the right terminology..
I have a list that looks like so:
list = ["abc",
"ded"]
I know how to append elements to this list, how to add elements to the beginning, etc.
What I need to do is to add a string (more specifically an asterisk (*)) before and after each object in this list. So it should look like:
list = ["*abc*",
"*ded*"]
I have tried:
asterisk = '*'
list = [asterisk] + list[0]
list = asterisk + List[0]
list = ['*'] + list[0]
list = * + list[0]
asterisk = list(asterisk)
list = [asterisk] + list[0]
and I always get:
TypeError: can only concatenate list (not "str") to list
Then of course there is the problem with adding it before and after each of the objects in the list.
Any help will be appreciated.
Just string interpolate it in as follows:
[f'*{s}*' for s in ["abc","ded"]]
Output
['*abc*', '*ded*']
Note this is for Python 3.6+ only.
For your list you use this beautiful syntax, called "list comprehension":
lst = ['abc', 'ded']
lst = ['*'+s+'*' for s in lst]
print(lst)
This would get you:
['*abc*', '*ded*']
Have you tried using a list comprehension to adjust
[('*'+i) for i in asterix]
you can give it a name just for good measure so that you can call it later
You can join the asterisks with each word
asterisked = [w.join('**') for w in lst]
The trick here is to remember that strings are iterables, so you can pass a string that contains two asterisks to the word's join method to let it prepend the word with the first asterisk and append the second one

unable to delete all element satisfying condition in a python list using enumerate

i am trying to delete zero values from the list using the below code
for id,row in enumerate(list):
if row[0]=="0":
del list(id)
this works fine for input like
[0,1,3,0,9,10,0,3,0,6]
but doesn't work as expected for inputs like
[0,0,1,3,4,0,0,4,5,6,0,0].
output: [0,1,3,4,0,4,5,6,0]
I guess its because the element right after the deleted one gets the id of the deleted element and enumerate increments the id which leaves the element after the one which is deleted unchecked.
so what can be done to check all the elements ? is there a better way ?
I made a little change to your code:
mylist = [0,0,1,3,4,0,0,4,5,6,0,0]
for id,row in reversed(list(enumerate(mylist))):
if(row==0):
del mylist[id]
If you loop your list in the way you did (from start to end) and delete an element while doing it, you'll end up jumping indexes because python does not recognize that an element has been deleted from the list.
If you have an array with 10 elements inside and you delete the first (idx 0), in the next iteration you will be at index 1, but the array has been modified, so your idx 1 is the idx 2 of your array before the deletion, and the real idx 1 will be skipped.
So you just need to loop your array in reverse mode, and you won't miss indexes.
If you print the value of mylist, you'll get [1, 3, 4, 4, 5, 6].
This problem is documented on this python page under 8.3:
https://docs.python.org/3/reference/compound_stmts.html
They suggest doing it this way by using a slice. It works for me:
a = [-2,-4,3,4]
for x in a[:]:
if x < 0: a.remove(x)
print ('contents of a now: ')
print(*a)
enumerate returns an object called enumerate object and it is iterable not actually a list. second thing row is not a list it is not subscriptable.
for i,row in enumerate(l):
if row==0:
del(l[i])
you will not get result you want this way.
try this:
t=[] #a temporary list
for i in l:
if i!=0:
t.append(i)
t will contain sublist of l with non zero elements.
put the above inside a function and return the list t .

Resources