Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a bit of a problem understanding what is going on inside of an insert method in python. I have been trying to manually insert elements into an empty array, some of them are working just fine but the other ones (index 2 and index 3) ara swapped. So here in this picture I believe 'q' should be in the index of 2 and 'd' in the index of '3' but it is the other way around. I understand that when I assign 'd' on index 3, there is not enough elements in blist array to insert on 3rd index.
blist = []
blist.insert(1, "h")
blist.insert(3, "d")
blist.insert(2, "q")
blist.insert(0, "g")
blist.insert(4, "k")
intended output: ['g', 'h', 'q', 'd', 'k']
output: ['g', 'h', 'd', 'q', 'k']
if someone could help me understand what I might be doing wrong, it would be much appreciated.
If the index you are inserting in is higher than the length of the list, the string will be inserted at the end of the list.
That means if you run:
blist = []
blist.insert(1, "h")
blist.insert(3, "d")
the list will look like this:
["h","d"]
if you now run: blist.insert(2, "q") it will put q at index 2 (the end of the list)
The code is working completely fine.
Below is the explanation of what is happening at each step.
At this point there is one element in the list.
blist.insert(1, "h")
['h']
The index of h -> 0
blist.insert(3, "d")
['h', 'd']
At this point d is inserted at index 3 but as there is only one element in the list its index in the list is d -> 1
blist.insert(2, "q")
['h', 'd', 'q']
A similar thing happens for 2 as well, it is inserted at index 2 and its index in the list becomes q -> 2
Same thing is happening on further insertions
blist.insert(0, "g")
['g', 'h', 'd', 'q']
blist.insert(4, "k")
['g', 'h', 'd', 'q', 'k']
If you specifically want an array. Arrays need to first be imported, or declared, from other libraries (i.e. numpy).
if the index at which you want to insert the item does not exist it will be inserted at another position.
i recommend running code in this environment, so you can see what happens at each step, and where the items get inserted:
http://pythontutor.com/visualize.html#mode=edit
A list of the different list methods can be found:
https://www.w3schools.com/python/python_ref_list.asp
Related
I'm learning python and I have been trying to make an automatic list of lists. For example:
The next list, which I have to split to get a list of separated letters, and then join them again to make a two lists of separated letters
lists=[['a,b,c,h'],['d,e,f,g']]
print('list length', len(lists))
splited=[]
splited1=lists[0][0].split(',')
print(splited1) #['a', 'b', 'c', 'h']
splited2=lists[1][0].split(',')
print(splited2) #['d', 'e', 'f', 'g']
listcomb=[splited1,splited2]
print(listcomb) #[['a', 'b', 'c', 'h'], ['d', 'e', 'f', 'g']]
This is what I want to get, a list that have 2 lists, but in the case I have to get more lists inside that list i want to make it automatic with a for loop.
My try, but it didn't work
listcomb2=zip(splited1,splited2)
print(listcomb2)
sepcomb = list()
print(type(sepcomb))
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
print(sepcomb)
I'm having problems with splitting the letters and then joining them in a new list. Pls help
Make some tweak in your code. As we can see lenght of sepcomb is 0 so use append method to avoid this problem. As sepcomb[x]=[sep] is is assignment to x-index but it x index doesn't exist so, it will raise error
change:
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
to
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb.append(sep)
Method-2
sepcomb = list(i[0].split(',') for i in lists)
You can simply do the following:
final=[splinted1]+[splinted2]
Or a better way directly from the lists variable would be:
final=[value[0].split(',') for value in lists]
Here you go:
lists = [['a,b,c,h'],['d,e,f,g']]
listcomb = []
for each in lists:
splited = each[0].split(',')
listcomb.append(splited)
print(listcomb)
This question already has answers here:
Splitting a string by list of indices
(4 answers)
Closed 4 years ago.
I would like to create a new list with sub-lists inside whose length depends on another list, for example I have:
a = [1,3,2,5,4]
b = ['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q']
and I would like to have a nested list of the form:
[['a'],
['b', 'c', 'd'],
['e', 'f'],
['g', 'h', 'i', 'l', 'm'],
['n', 'o', 'p', 'q']]
Steps to solve this:
create an empty list
create a int done=0 that tells you how many things you already sliced from your data
loop over all elements of your "how to cut the other list in parts"-list
slice from done to done + whatever the current element of your "how to cut the other list in parts" is and append it to the empty list
increment done by whatever you just sliced
add the (if needed) remainder of your data
print it.
Doku:
Understanding Python's slice notation
How to "properly" print a list?
and infos about looping here: looping techniques PyTut
You can read about why we do not solve your homework for you here: open letter to students with homework problems
a = [1,3,2,5,4]
b = ['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q']
out=[]
for number in a:
out.append(b[:number])
b=b[number:]
print(out)
#[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i', 'l', 'm'], ['n', 'o', 'p', 'q']]
Description
The out is the final output list. The loop iterates through each element in list a (say 'number') and appends a list of that many elements from the start of list b to our output list. Then it proceeds to update list b so that those elements are removed.
I want to create a list say chelsea_fc that will populate the value "EPL Champions" in even indexes and "Manager Sacked" at odd indexes till a given range. (dont want to hard code the range)
I am getting confused as how to do it. Please help
Literally write it as you would say it!
>>> ['a' if i % 2 else 'b' for i in range(10)]
['b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']
You can do this (or any other list that repeat itself) like this:
chelsea_fc = ['Manager Sacked', 'EPL Champions']*(range_of_choice/2)
print(chelsea_fc)
This question already has answers here:
How to iterate over a list in chunks
(39 answers)
Closed 5 years ago.
I have 15 elements in an array and I want to allocate each five of them to a block respectively. The elements are:
elements=["a",'b','c','d','e','f','g','h','i','j','k','l','m','n','o']
I wanted to say first 5 elements are belonged to block#1, second five are belonged to block#2 and so on. I need to do it in a loop structure as later on, I need to use the information of each block for a special task. As I am new to python I don't know how to write it. Any advice will be highly appreciated.
You can simply use list comprehension for that:
result = [elements[i:i+5] for i in range(0,len(elements),5)]
which will generate:
>>> result
[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'j'], ['k', 'l', 'm', 'n', 'o']]
Or more generic:
def blockify(elements,n=5):
return [elements[i:i+n] for i in range(0,len(elements),n)]
and then call it with blockify(elements,5).
What we do is we create a range that ranges from 0 to the len(elements) (length of the elements), and makes hops of 5 (or n in the generic case). Now for each of these steps, we add a slice elements[i:i+5] to the result.
Loop through all and divide index by 5 (floor division operator //)
The result of dividing is number of group.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a list:
a=['I', 'O', 'O', 'I', 'I', 'O', 'O', 'I', 'I', 'U', 'U', 'I', 'I', 'S', 'S', 'I', 'X', 'X', 'X', 'X']
I want to process the list so that
if a[0]=='I': it would remove the next 'I'
if a[0]=='O' it would remove the next 3 'O''s
if a[0]=='U' it would remove the next 'U'
S and X don't do anything
and then a[1] ... until reaching the end
the result of a would be
a=['I','O','I','I','U','I','S','S','X','X','X','X']
it doesn't necessarily need to be the same list I can create another one.
first you want to loop until a[0] is 'X' or 'S'
while a[0] not in "XS": # this will break if a is ever totally empty ...
if a[0] == "I":
a = takeNext(a,"I")
elif a[0] == "O":
a = takeNext(a,"O",3)
elif a[0] == "U":
a = takeNext(a,"U")
then all you have to do is write a takeNext method that looks something like
def takeNext(a_list,whatToTake,howManyToTake=1):
#write this function
#keep in mind you will also have to define some edge cases
#what happens if the list doesnt have what you should remove
#or only has 2 when you are supposed to take 3
keep in mind that this is a little bit over simplified there are several edge cases that do not have defined behaviour, based on your problem statement, so you will have to put some work in to define edge cases and their behaviour (I did include some examples of edge cases, but I make no claim that that is all the edge cases)