How to Change position of elements in python list - python-3.x

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.

Related

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?

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]

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

accessing specific intervals in list

I have a list containing the system time from a machine. Since the list contains only the milliseconds part, the values donĀ“t go beyond 1000.
For better viewing I want to add i*1000 to certain intervals in this list for each time the list skips 1000. For better understanding i will give my input list and what my output list should look like:
inputlist = [300,600,900,200,500,800,100,400]
etc, the output list should look like this:
outputlist = [300,600,900,1200,1500,1800,2100,2400]
since I want the list to start with zero i subtracted the first element of the list from each element giving me a new inputlist:
inputlist_new = [0,300,600,-100,200,500,-200,100]
which should give me a new outputlist like:
outputlist_new = [0,300,600,900,1200,1500,1800,2100]
I tried creating a list containing the indices of each element < 0 to cut the list into intervals, to multiply the thousands on each interval but I am not able to do so. My code for this index list is this:
list_index = [i for i, j in enumerate(inputlist_new) if j < 0]
I actually found a solution myself: i copied the list i want to change into a new one, just for the sake of maybe using it later (so this is not necessary for the solution) and then used 2 for loops:
inputlist_new = [0,300,600,-100,200,500,-200,100]
inputlist2 = inputlist_new.copy()
for x in range(len(list_index)):
for y in range(list_index[x],len(inputlist2)):
inputlist2[y] = inputliste2[y]+1000
this gave me the wanted output

python3 functional programming: Accumulating items from a different list into an initial value

I have some code that performs the following operation, however I was wondering if there was a more efficient and understandable way to do this. I am thinking that there might be something in itertools or such that might be designed to perform this type of operation.
So I have a list of integers the represents changes in the number of items from one period to the next.
x = [0, 1, 2, 1, 3, 1, 1]
Then I need a function to create a second list that accumulates the total number of items from one period to the next. This is like an accumulate function, but with elements from another list instead of from the same list.
So I can start off with an initial value y = 3.
The first value in the list y = [3]. The I would take the second
element in x and add it to the list, so that means 3+1 = 4. Note that I take the second element because we already know the first element of y. So the updated value of y is [3, 4]. Then the next iteration is 4+2 = 6. And so forth.
The code that I have looks like this:
def func():
x = [0, 1, 2, 1, 3, 1, 1]
y = [3]
for k,v in enumerate(x):
y.append(y[i] + x[i])
return y
Any ideas?
If I understand you correctly, you do what what itertools.accumulate does, but you want to add an initial value too. You can do that pretty easily in a couple ways.
The easiest might be to simply write a list comprehension around the accumulate call, adding the initial value to each output item:
y = [3 + val for val in itertools.accumulate(x)]
Another option would be to prefix the x list with the initial value, then skip it when accumulate includes it as the first value in the output:
acc = itertools.accumulate([3] + x)
next(acc) # discard the extra 3 at the start of the output.
y = list(acc)
Two things I think that need to be fixed:
1st the condition for the for loop. I'm not sure where you are getting the k,v from, maybe you got an example using zip (which allows you to iterate through 2 lists at once), but in any case, you want to iterate through lists x and y using their index, one approach is:
for i in range(len(x)):
2nd, using the first append as an example, since you are adding the 2nd element (index 1) of x to the 1st element (index 0) of y, you want to use a staggered approach with your indices. This will also lead to revising the for loop condition above (I'm trying to go through this step by step) since the first element of x (0) will not be getting used:
for i in range(1, len(x)):
That change will keep you from getting an index out of range error. Next for the staggered add:
for i in range(1, len(x)):
y.append(y[i-1] + x[i])
return y
So going back to the first append example. The for loop starts at index 1 where x = 1, and y has no value. To create a value for y[1] you append the sum of y at index 0 to x at index 1 giving you 4. The loop continues until you've exhausted the values in x, returning accumulated values in list y.

Switching positions of two strings within a list

I have another question that I'd like input on, of course no direct answers just something to point me in the right direction!
I have a string of numbers ex. 1234567890 and I want 1 & 0 to change places (0 and 9) and for '2345' & '6789' to change places. For a final result of '0678923451'.
First things I did was convert the string into a list with:
ex. original = '1234567890'
original = list(original)
original = ['0', '1', '2' etc....]
Now, I get you need to pull the first and last out, so I assigned
x = original[0]
and
y = original[9]
So: x, y = y, x (which gets me the result I'm looking for)
But how do I input that back into the original list?
Thanks!
The fact that you 'pulled' the data from the list in variables x and y doesn't help at all, since those variables have no connection anymore with the items from the list. But why don't you swap them directly:
original[0], original[9] = original[9], original[0]
You can use the slicing operator in a similar manner to swap the inner parts of the list.
But, there is no need to create a list from the original string. Instead, you can use the slicing operator to achieve the result you want. Note that you cannot swap the string elements as you did with lists, since in Python strings are immutable. However, you can do the following:
>>> a = "1234567890"
>>> a[9] + a[5:9] + a[1:5] + a[0]
'0678923451'
>>>

Resources