I tried writing some code like:
i = [1, 2, 3, 5, 8, 13]
j = []
k = 0
for l in i:
j[k] = l
k += 1
But I get an error message that says IndexError: list assignment index out of range, referring to the j[k] = l line of code. Why does this occur? How can I fix it?
j is an empty list, but you're attempting to write to element [0] in the first iteration, which doesn't exist yet.
Try the following instead, to add a new element to the end of the list:
for l in i:
j.append(l)
Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:
j = list(i)
Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None in the example below), and later, overwrite the values in specific positions:
i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0
for l in i:
j[k] = l
k += 1
The thing to realise is that a list object will not allow you to assign a value to an index that doesn't exist.
Your other option is to initialize j:
j = [None] * len(i)
Do j.append(l) instead of j[k] = l and avoid k at all.
You could also use a list comprehension:
j = [l for l in i]
or make a copy of it using the statement:
j = i[:]
j.append(l)
Also avoid using lower-case "L's" because it is easy for them to be confused with 1's
I think the Python method insert is what you're looking for:
Inserts element x at position i.
list.insert(i,x)
array = [1,2,3,4,5]
# array.insert(index, element)
array.insert(1,20)
print(array)
# prints [1,20,2,3,4,5]
You could use a dictionary (similar to an associative array) for j
i = [1, 2, 3, 5, 8, 13]
j = {} #initiate as dictionary
k = 0
for l in i:
j[k] = l
k += 1
print(j)
will print :
{0: 1, 1: 2, 2: 3, 3: 5, 4: 8, 5: 13}
One more way:
j=i[0]
for k in range(1,len(i)):
j = numpy.vstack([j,i[k]])
In this case j will be a numpy array
Maybe you need extend()
i=[1,3,5,7]
j=[]
j.extend(i)
Related
I tried writing some code like:
i = [1, 2, 3, 5, 8, 13]
j = []
k = 0
for l in i:
j[k] = l
k += 1
But I get an error message that says IndexError: list assignment index out of range, referring to the j[k] = l line of code. Why does this occur? How can I fix it?
j is an empty list, but you're attempting to write to element [0] in the first iteration, which doesn't exist yet.
Try the following instead, to add a new element to the end of the list:
for l in i:
j.append(l)
Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:
j = list(i)
Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None in the example below), and later, overwrite the values in specific positions:
i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0
for l in i:
j[k] = l
k += 1
The thing to realise is that a list object will not allow you to assign a value to an index that doesn't exist.
Your other option is to initialize j:
j = [None] * len(i)
Do j.append(l) instead of j[k] = l and avoid k at all.
You could also use a list comprehension:
j = [l for l in i]
or make a copy of it using the statement:
j = i[:]
j.append(l)
Also avoid using lower-case "L's" because it is easy for them to be confused with 1's
I think the Python method insert is what you're looking for:
Inserts element x at position i.
list.insert(i,x)
array = [1,2,3,4,5]
# array.insert(index, element)
array.insert(1,20)
print(array)
# prints [1,20,2,3,4,5]
You could use a dictionary (similar to an associative array) for j
i = [1, 2, 3, 5, 8, 13]
j = {} #initiate as dictionary
k = 0
for l in i:
j[k] = l
k += 1
print(j)
will print :
{0: 1, 1: 2, 2: 3, 3: 5, 4: 8, 5: 13}
One more way:
j=i[0]
for k in range(1,len(i)):
j = numpy.vstack([j,i[k]])
In this case j will be a numpy array
Maybe you need extend()
i=[1,3,5,7]
j=[]
j.extend(i)
I have this list of values:
A = [0,0,1,2,3,4,5,6,0,6,6,8,8,0,0,2,3,4,5,12,45,-0,-0,-9,-2,3,-0,-2,-2,-2]
I want to get this list of values for the output :
A = [1,2,3,4,5,6,0,6,6,8,8,2,3,4,5,12,45,-9,-2,3,-0,-2,-2,-2]
Basically, I want to drop the consecutive zeros only, and keep all the other values.
Do you have any idea on how i can do that ? I tried this one but i know there will be in index error :
X = []
for j in range(len(A)):
if A[j] != 0 and A[j+1] != 0:
X.append(A[j])
else:
print('lol')
print(X)```
You can use itertools.groupby and itertools.chain:
from itertools import groupby, chain
out = list(chain.from_iterable(G for k,g in groupby(A)
if len(G:=list(g))<2 or k!=0))
Explanation:
groupby will group the consecutive values. For each group, if the length is no more than 1 or the key (=value) is not 0, keep it. Finally chain all the groups together and convert to list.
Note that groupby returns iterators so I am using an assignment expression to perform the conversion.
output:
[1, 2, 3, 4, 5, 6, 0, 6, 6, 8, 8, 2, 3, 4, 5, 12, 45, -9, -2, 3, 0, -2, -2, -2]
With itertools:
from itertools import groupby
X = [x
for x, [*xs] in groupby(A)
if x or len(xs) == 1
for x in xs]
Alternatively:
X = []
for x, [*xs] in groupby(A):
if x or len(xs) == 1:
X += xs
Or taking any x that's not zero or where the previous and next values are not zero (padding with 1):
X = [x
for p, x, n in zip([1]+A, A, A[1:]+[1])
if x or p and n]
if u dont want to import itertools and prefer list comprehension
A = [i for index,i in enumerate(A) if i!=0 or index not in [0,len(A)] and A[index-1]!=i and A[index+1]!=i ]
note that this expressions uses the precedence of and operator over or operator
enumerate is used too
Here's a more simple, easy, and bit lengthy than other answers method to solve your problem
A = [0,0,1,2,3,4,5,6,0,6,6,8,8,0,0,2,3,4,5,12,45,-0,-0,-9,-2,3,-0,-2,-2,-2]
ind=[i for i,j in enumerate(A) if j==0]
C=[(ind[i],ind[i+1]) for i in range(len(ind)-1) if ind[i]+1==ind[i+1]]
D=[i for i1 in C for i in i1]
E=["" if i in D else j for i,j in enumerate(A)]
F=[i for i in E if i!=""]
# TEST
d_output=[1,2,3,4,5,6,0,6,6,8,8,2,3,4,5,12,45,-9,-2,3,-0,-2,-2,-2]
print(F==d_output)
Output: 1 i.e Your desired output
If you want to specify the value, then you can wrap it up in a function as below:
def remove_c(list_2,val):
ind=[i for i,j in enumerate(list_2) if j==val]
C=[(ind[i],ind[i+1]) for i in range(len(ind)-1) if ind[i]+1==ind[i+1]]
D=[i for i1 in C for i in i1]
E=["" if i in D else j for i,j in enumerate(A)]
return [i for i in E if i!=""]
print(remove_c(A,10))
Explantion:
I have taken all the indexes of 0 in the list.
Checked if the indexes are consecutive or not. If they are, then append them in the list C in tuple.
And, because the list C contains tuple, created a flat list D out of list C.
Replaced the indexes of list D with "".
Removed "" for the list.
I have noticed a silly mistake in your code:
X = []
for j in range(len(A)): # Mistake here
if A[j] != 0 and A[j+1] != 0: # if we bypassed the above error we can also get error here
X.append(A[j])
else:
print('lol')
print(X)
The problem is when the i is at last index of the list, there would be no other index but you have hard-coded to search for index+1, so it would throw an error.
There are 2 method to solve this:
Use try and except.
Replace range(len(A) to range(len(A)-1).
This permutation comes from Udacity and is made with Python.
But i have problems to understand what does it means +1 in this line for j in range(0, len(p) + 1):. Someone could help me to understand it? I'm little bit confused.
Thanks to all!
import copy
def permute(l):
perm = []
if len(l) == 0:
perm.append([])
else:
first_element = l[0]
after_first = slice(1, None)
sub_permutes = permute(l[after_first])
for p in sub_permutes:
for j in range(0, len(p) + 1):
r = copy.deepcopy(p)
r.insert(j, first_element)
perm.append(r)
return perm
The idea behind this loop is to create a lists each with first_element in different place.
To insert an element after the last index (mimic append behavior), you would write l.insert(len(l), element)). So when they are trying to insert the first element in each place of the list they want the range to be from 0 to len(p) and be inclusive, so they add +1 to the range.
In [1]: l = [1,2,3]
In [2]: for i in range(0, len(l)+1):
...: new_l = list(l)
...: new_l.insert(i, 4)
...: print(new_l)
...:
[4, 1, 2, 3]
[1, 4, 2, 3]
[1, 2, 4, 3]
[1, 2, 3, 4] # without the +1 this line would not be created
I am trying to amend a list of integers in a way that every 2 duplicating integers will be multiplied by 2 and will replace the duplicates. here is an example:
a = [1, 1, 2, 3] = [2, 2 ,3] = [4 ,3]
also : b = [2, 3, 3, 6 ,9] = [2 , 6 , 6, 9] = [2, 12 , 9]
I am using the code below to achieve this. Unfortunately, every time I find a match my index would skip the next match.
user_input = [int(a) for a in input().split()]
for index, item in enumerate(user_input):
while len(user_input)-2 >= index:
if item == user_input[index + 1]:
del user_input[index]
del user_input[index]
item += item
user_input.insert(index,item)
break
print(*user_input)
In Python, you should never modify a container object while you are iterating over it. There are some exceptions if you know what you are doing, but you certainly should not change the size of the container object. That is what you are trying to do and that is why it fails.
Instead, use a different approach. Iterate over the list but construct a new list. Modify that new list as needed. Here is code that does what you want. This builds a new list named new_list and either changes the last item(s) in that list or appends a new item. The original list is never changed.
user_input = [int(a) for a in input().split()]
new_list = []
for item in user_input:
while new_list and (item == new_list[-1]):
new_list.pop()
item *= 2
new_list.append(item)
print(*new_list)
This code passes the two examples you gave. It also passes the example [8, 4, 2, 1, 1, 7] which should result in [16, 7]. My previous version did not pass that last test but this new version does.
Check if this works Rory!
import copy
user_input = [1,1,2,3]
res = []
while res!=user_input:
a = user_input.pop(0)
if len(user_input)!=0
b = user_input.pop(0)
if a==b:
user_input.insert(0,a+b)
else:
res.append(a)
user_input.insert(0,b)
else:
res.append(a)
user_input = copy.deepcopy(res)
You can use itertools.groupby and a recursion:
Check for same consecutive elements:
def same_consec(lst):
return any(len(list(g)) > 1 for _, g in groupby(lst))
Replace consecutive same elements:
def replace_consec(lst):
if same_consec(lst):
lst = [k * 2 if len(list(g)) > 1 else k for k, g in groupby(lst)]
return replace_consec(lst)
else:
return lst
Usage:
>>> a = [8, 4, 2, 1, 1, 7]
>>> replace_consec(a)
[16, 7]
I tried writing some code like:
i = [1, 2, 3, 5, 8, 13]
j = []
k = 0
for l in i:
j[k] = l
k += 1
But I get an error message that says IndexError: list assignment index out of range, referring to the j[k] = l line of code. Why does this occur? How can I fix it?
j is an empty list, but you're attempting to write to element [0] in the first iteration, which doesn't exist yet.
Try the following instead, to add a new element to the end of the list:
for l in i:
j.append(l)
Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:
j = list(i)
Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None in the example below), and later, overwrite the values in specific positions:
i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0
for l in i:
j[k] = l
k += 1
The thing to realise is that a list object will not allow you to assign a value to an index that doesn't exist.
Your other option is to initialize j:
j = [None] * len(i)
Do j.append(l) instead of j[k] = l and avoid k at all.
You could also use a list comprehension:
j = [l for l in i]
or make a copy of it using the statement:
j = i[:]
j.append(l)
Also avoid using lower-case "L's" because it is easy for them to be confused with 1's
I think the Python method insert is what you're looking for:
Inserts element x at position i.
list.insert(i,x)
array = [1,2,3,4,5]
# array.insert(index, element)
array.insert(1,20)
print(array)
# prints [1,20,2,3,4,5]
You could use a dictionary (similar to an associative array) for j
i = [1, 2, 3, 5, 8, 13]
j = {} #initiate as dictionary
k = 0
for l in i:
j[k] = l
k += 1
print(j)
will print :
{0: 1, 1: 2, 2: 3, 3: 5, 4: 8, 5: 13}
One more way:
j=i[0]
for k in range(1,len(i)):
j = numpy.vstack([j,i[k]])
In this case j will be a numpy array
Maybe you need extend()
i=[1,3,5,7]
j=[]
j.extend(i)