how can i append in reverse? python - python

.append
Function adds elements to the list.
How can I add elements to the list? In reverse? So that index zero is new value, and the old values move up in index?
What append does
[a,b,c,d,e]
what I would like.
[e,d,c,b,a]
Thank you very much.

Suppose you have a list a, a = [1, 2, 3]
Now suppose you wonder what kinds of things you can do to that list:
dir(a)
Hmmmm... wonder what this insert thingy does...
help(a.insert)
Insert object before index, you say? Why, that sounds a lot like what I want to do! If I want to insert something at the beginning of the list, that would be before index 0. What object do I want to insert? Let's try 7...
a.insert(0, 7)
print a
Well, look at that 7 right at the front of the list!
TL;DR: dir() will let you see what's available, help() will show you how it works, and then you can play around with it and see what it does, or Google up some documentation since you now know what the feature you want is called.

It would be more efficient to use a deque(double-ended queue) for this. Inserting at index 0 is extremely costly in lists since each element must be shifted over which requires O(N) running time, in a deque the same operation is O(1).
>>> from collections import deque
>>> x = deque()
>>> x.appendleft('a')
>>> x.appendleft('b')
>>> x
deque(['b', 'a'])

Use somelist.insert(0, item) to place item at the beginning of somelist, shifting all other elements down. Note that for large lists this is a very expensive operation. Consider using deque instead if you will be adding items to or removing items from both ends of the sequence.

Using Python's list insert command with 0 for the position value will insert the value at the head of the list, thus inserting in reverse order:
your_list.insert(0, new_item)

You can do
your_list=['New item!!']+your_list
But the insert method works as well.

lst=["a","b","c","d","e","f"]
lst_rev=[]
lst_rev.append(lst[::-1])
print(lst_rev)

Here's an example of how to add elements in a list in reverse order:
liste1 = [1,2,3,4,5]
liste2 = list()
for i in liste1:
liste2.insert(0,i)

Use the following (assuming x is what you want to prepend):
your_list = [x] + your_list
or:
your_list.insert(0, x)

Related

How to add up values of the "sublists" within a list of lists

I have a list of lists in my script:
list = [[1,2]
[4,3]
[6,2]
[1,6]
[9,2]
[6,5]]
I am looking for a solution to sum up the contents of each "sublist" within the list of lists. The desired output would be:
new_list = [3,7,8,7,11,11]
I know about combining ALL of these lists into one which would be:
new_list = [27,20]
But that's not what i'm looking to accomplish.
I need to combine the two values within these "sublists" and have them remain as their own entry in the main list.
I would also greatly appreciate it if it was also explained how you solved the problem rather than just handing me the solution. I'm trying to learn python so even a minor explanation would be greatly appreciated.
Using Python 3.7.4
Thanks, Riftie.
The "manual" solution will be using a for loop.
new_list = []
for sub_list in list:
new_list.append(sum(sub_list))
or as list compherension:
new_list = [sum(sub_list) for sub_list in list]
The for loop iterates through the elements of list. In your case, list is a list of lists. So every element is a list byitself. That means that while iterating, sub_list is a simple list. To get a sum of list I used sum() build-in function. You can of course iterate manually and sum every element:
new_list = []
for sub_list in list:
sum_val = 0
for element in sub_list:
sum_val = sum_val + element
new_list.append(sum_val)
but no need for that.
A better approach will be to use numpy, which allows you to sum by axis, as it looks on list of lists like an array. Since you are learning basic python, it's too soon to learn about numpy. Just keep in mind that there is a package for handling multi-dimensions arrays and it allows it perform some actions like sum on an axis by your choice.
Edit: I've seen the other solution suggest. As both will work, I believe this solution is more "accessible" for someone who learn to program for first time. Using list comprehension is great and correct, but may be a bit confusing while first learning. Also as suggested, calling your variables list is a bad idea because it's keyword. Better names will be "my_list", "tmp_list" or something else.
Use list comprehension. Also avoid using keywords as variable names, in your case you overrode the builtin list.
# a, b -> sequence unpacking
summed = [a + b for a, b in lst] # where lst is your list of lists
# if the inner lists contain variable number of elements, a more
# concise solution would be
summed2 = [sum(seq) for seq in lst]
Read more about the powerful list comprehension here.

How do I add an element inside a list which is inside a list?

l = [1,2,3,[4,5,6]]
I want
l = [1,2,3,[4,5,6,7]]
Now I want to add 7 in the list which is inside the list.
I applied the same logic as accessing [3][3]
l.insert("index","value") #syntax
l.insert([3][3],7)
But it isn't working. I couldn't solve it with append as well.
You want to add a 7 to the element at index 3 in l.
That is:
l[3].append(7)
you can do the following:
l[3].insert(3,7)
What's wrong with your approach? In the insert(index, value) method the index should be an integer. The [3][3] you are passing, is not an integer. Moreover, it is not even a valid value (meaning, you can't write eg x = [3][3].
The [i] after an object calls its __getitem__ method internally. So, what you are trying to do is
get the element 3 of the initial list
hope that what you get is a list
insert on position 3 of that list
So, you can do that
inner_list = mylist[3]
inner_list.insert(3, 7)
or, more compactly mylist[3].insert(3, 7)
If you want to insert at the last position, you could as well write mylist[3].append(7)
Here l[3][3] is an int. Ofcouse it will not work as there are no built-ins defined such as insert and append on int
While l[3] is of list type so it supports both of those functions
l[3].append(7) or l[3].insert(3,7)
Also lists are mutable type so making a change in inner list will be reflected in the outer list as well. Hope it helps
you can access to that 7 with:
l[3][3]

with just four element getting the Memory error in python

I have been getting the memory error but unable to understand the reason behind that. Below is the code. Using the list and appending just two more elements in the list.
mylist = ['phonon', 'communication']
for i in mylist:
mylist.append(i.upper())
print(mylist)
It will be really very helpful if anyone can help me with that.
for i in mylist:
mylist.append(i.upper())
is basically appending to your list while iterating on it. So the iteration never ends.
You want to do:
mylist += [i.upper() for i in mylist]
in that last case, the right-hand expression is computed from a non-modified mylist, then its elements are appended to the existing mylist.
note that the above is equivalent to
mylist.extend([i.upper() for i in mylist])
or
mylist.extend(list(map(str.upper,mylist)))
note that for both snippets above it is necessary to convert to list, or you get the same memory error if the inside is lazily evaluated. The last snippet is probably the fastest because it doesn't use any python loops at all, map, and no lambda
For all 3 snippets the result is:
['phonon', 'communication', 'PHONON', 'COMMUNICATION']
I would add your edited elements to a new list:
uppers = []
for i in mylist:
uppers.append(i.upper())
print(uppers)
Building off Jean's answer:
mylist.extend(i.upper() for i in mylist)
Should give you the desired result.

Deleting Numbers From A String -Python

I am creating a program for a high school course and our teacher is very specific about what is allowed into our programs. We use python 2.x and he only allows if statements, while loops, functions, boolean values, and lists. I am working on a project that will print the reversal of a string, then print again the same reversal without the numbers in it but I cannot figure it out. Help please. What i have so far is this..
def reverse_str(string):
revstring =('')
length=len(string)
i = length - 1
while i>=0:
revstring = revstring + string[i]
i = i - 1
return revstring
def strip_digits(string):
l = [0,1,2,3,4,5,6,7,8,9]
del (l) rev_string
string = raw_input("Enter a string->")
new_str = rev_str(string)
print new_str
I cannot figure out how to use the "del" function properly, how do i delete any of the items in the list from the reversed string..thanks
In general, you have two options for a task like this:
Iterate through the items in your list, deleting the ones that you do not want to keep.
Iterate through the items in your list, copying the ones that you do want to keep to a new list. Return the new list.
Now, although I would normally prefer option (2), that won't help with your specific question about del. To delete an item at index x from a list a, the following syntax will do it:
del a[x]
That will shift all the elements past index x to the left to close the gap left by deleting the element. You will have to take this shift into account if you're iterating through all the items in the list.
Type str in python is immutable (cannot be altered in place) and does not support the del item deletion function.
Map the characters of the string to a list and delete the elements you want and reconstruct the string.
OR
Iterate through the string elements whilst building a new one, omitting numbers.
correct usage of del is:
>>> a = [1, 2, 3]
>>> del a[1]
>>> a
[1, 3]
You could iterate back over the string copying it again but not copying the digits... It would be interesting for you to also figure out the pythonic way to do everything your not allowed to. Both methods are good to know.

What is the right way to create a list from variable and another list?

This is the only way i can think of looks like this:
var = 1
list = [2, 3, 4]
newList = [var,] + list
Is it the right way?
Update: I need to make a new list so insert would not help
Your method is fine (other than the extra comma not needed for a 1-list); people have done it this way for a long time.
In general you want to avoid adding things to the start of a list in Python: it's O(n) in cost.
If you have to (and often the inefficiency doesn't matter), you can do this:
[a] + other_list
If you don't mind updating the list you have, you can do this:
other_list.insert(0, a)
If you can use an iterator rather than a list, you can efficiently use:
itertools.chain([a], other_list)
I am not sure what you want to imply by using the , after var but generally you won;t need it. As you were trying to get other options here is another way to do
lst.insert(0,var)
If you are not intending to modify the original list you may want to copy it to another list
newList=lst[::]
and then do the insert
lst.insert(0,var)
It's a matter of style but I prefer
newList=[var]+lst
Note**
Generally if you are not intending to modify the original list,
newlst = [var] + lst
looks cleaner
but in case you want to modify in place your options are
lst = [var] + lst
or
lst.insert(0,var)
The later one is preferable because it is more readable and moreover you can use it inside lambda and list-comprehension :-)
Use the append method:
list.append(var)
or insert of you want to place the new element in the beginning:
list.insert(0,var)
What about this?
a_list = []
v = 1
list_to_add = [2, 3, 4]
a_list.append(v)
a_list.extend(list_to_add)
For your reference, go through this LIST

Categories

Resources