Python list add range

Appending a range to a list

This is confusing to me, as my thought process is that the length of the initial list is 3, and appending range(2) to the end brings it to length of 5. Therefore I’d expect the output to be 5 6 5 . I’m sure it’s a simple quirk, but I’m a bit lost and having a hell of a time trying to find an answer online. Would anyone be able to point me in the right direction?

.append(range(2)) adds exactly one element to the list, always. So you’ve added [0, 1] to that list.

2 Answers 2

You appended a single list object. You did not add the elements from the list that range produces to L . A nested list object adds just one more element:

>>> L = ['a', 'bb', 'ccc'] >>> L.append(range(2)) >>> L ['a', 'bb', 'ccc', [0, 1]] 

Note the [0, 1] , the output of the range() function.

You are looking for list.extend() instead:

>>> L = ['a', 'bb', 'ccc'] >>> L.extend(range(2)) >>> L ['a', 'bb', 'ccc', 0, 1] >>> len(L) 5 

As an alternative to list.extend() , in most circumstances you can use += augmented assignment too (but take into account the updated L list is assigned back to L , which can lead to surprises when L was a class attribute):

>>> L = ['a', 'bb', 'ccc'] >>> L += range(2) >>> L ['a', 'bb', 'ccc', 0, 1] 

Insert A Range of item or to List anywhere

 g=[1,2,3,4,7,8] z=[5,6] def insertRange(start,YourList,anotherlist): if isinstance(YourList,list) and isinstance(anotherlist,list) : YourlistPart1=YourList[0:start] YourlistPart2=YourList[start:] YourlistPart1.extend(anotherlist) YourlistPart1.extend(YourlistPart2) print(YourlistPart1) insertRange(4,g,z) 

You can’t insert range in a specific location in python but you can work around by function using extend you can split your list extend first part and then merge the 2 lists again start= doesn’t start from 0 if you wish to start insert from index 3 which = 4 in the example you start with 3

Читайте также:  Скролл на телефоне css

start from 1 adds the list after the index 0 and shift the other elements

start from 4 adds the list after the index 3 and shift the other elements

start from 5 adds the list after the index 4

Источник

How to add a range of elements of a list to another list in python

I have list let’s say my_first_list = [«A», «M», «F», «T», «_», «D»] . I want to create another list with these elements: M, F, T so my second list would be my_second_list = [«M», «F», «T»] here is my code but it does not work. sorry I am a beginner.

def createProtein(seq): my_list = [] for i in seq: if i == "M": my_list.append(i) if i != "_": for j in range(len(my_list)): my_list[j] += i return my_list rframe = ["A", "M", "F", "T", "_", "D"] print(createProtein(rframe))``` 

What’s preventing you from just writing output = [‘M’, ‘F’, ‘T’] ? In other words, what’s the criterion for inclusion? The function name createProtein doesn’t really offer any clue …

2 Answers 2

You can use a slice to extract a range of elements from a list:

my_first_list = ["A", "M", "F", "T", "_", "D"] my_second_list = my_first_list[1:4] 

If you don’t know the indices, but want to use ‘M’ and ‘_’ as the bounds, you can use:

ix1 = my_first_list.index('M') ix2 = my_first_list.index('_') my_second_list = my_first_list[ix1:ix2] 

Was about to post the same answer, up-voted yours instead. 🙂 Note that index will raise an exception if the value is not found, but that’s probably for the best; if your list lacks the expected values, you can’t very well slice based on them.

Dear Tom, Thank you so much. as you mentioned I do not know the indices and I want to use a for loop because I do not know whether my first list contains ‘M’ and ‘_’. and I want to use them as the bound.

@ptalebic What I showed will find them if they are present. If you want to search with a loop, just save the indices and you can still use a slice to extract the range once you know it.

@ptalebic Another possibility is to wrap the two find invocations in a try / except to check if they’re present. If they are, and if ix1 < ix2`, then you're good. Otherwise you can give an error or do whatever recovery is appropriate.

You are making a huge mistake in your code.

def createProtein(seq): my_list = [] for i in seq: if i == "M": my_list.append(i) if i != "_": for j in range(len(my_list)): my_list[j] += i print(my_list) return my_list rframe = ["A", "M", "F", "T", "_", "D"] createProtein(rframe) # print(createProtein(rframe)) 

When i == ‘M’ , my_list will add ‘M’. It will again add an ‘M’ because of the j loop. In the next iteration, i will be ‘F’, hence i == ‘M’ will be false, and no code will be executed after that. Hence finally, my_list will be ‘MM’.

lis = ['A', 'M', 'F', 'T', '_', 'D'] def index(lis, c): for i in range(len(lis)): if lis[i] == c: return i def extract(lis, start, end): return lis[start : end] print(extract(lis, index(lis, 'M'), index(lis, '_'))) 

Now you can extract any sub list by passing the start and end characters to index() and then to extract() Output [‘M’, ‘F’, ‘T’]

Источник

Adding value to range of values in a list?

I want to create a new array by adding first element of array b to all the first set of ranges in array a and add second element of array b to all the second set of ranges in array a i.e.

 [[[4251+1324, 4254+1324], [4123+1324, 4290+1324]], [[4323+2745, 4222+2745], [4111+2745, 4900+2745]]] 

You probably should give a more readable example of data you are working with. Looking through 10+ lines of pure digits and braces is quite uninformative

Your new example is different from the previous one: the new one has a being a list of pairs, while the old had a being a list two sub-lists, each containing multiple pairs of numbers. This causes confusion.

What do you mean by ‘ranges’? If [4251, 4254] is a range, then why do you call a ‘an array of ranges’? I don’t get the structure of your data..

6 Answers 6

This should work for any length (provided a and b have the same length)

[[[i+b[k],j+b[k]] for (i,j) in a[k]] for k in range(len(a))] 
>>> pprint([[[i+b[k],j+b[k]] for (i,j) in a[k]] for k in range(len(a))]) [[[7880.1484209792943, 8171.6175205036743], [8225.6716915199249, 8378.3978601695999], [4729.0665464257172, 4732.276168393144], [5501.1899887058553, 5722.1839186014013], [360.55565340157807, 365.04589505745309], [20983.0, 20983.0], [217.14888548659997, 232.6226734478], [385.14888548659997, 400.62267344780003], [2823.2942485733347, 2840.4346062020377], [4502.0794526850004, 4700.9945330295996], [10417.852743984931, 10986.246567556096], [8191.6238503034892, 8194.8209578124479], [29570.28005012768, 29570.662880091983]], [[3250.5273987094843, 3252.7610916503263], [5593.4838299153871, 5596.0104208719731], [576.2276993911745, 622.11755144656183], [3188.3893120098983, 3206.7951214629902], [3246.2448304681798, 3250.0964343653186], [3272.9341862125516, 3274.8892802899418], [5969.1472437958755, 5971.2996518169357], [4255.3500559453041, 4258.126659789853]]] 

Источник

Append a Range to a List in Python

Python has a built-in method, called range(start, stop) , that allows you to easily create arrays whose values are integers, starting from start and ending before stop (exclusive). The following code creates a list of integers from 0 to 9:

>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

Providing only one argument to the range() method will create a list of integers from 0 to the value of the argument given.

Oftentimes you’ll want to create a range and add it to the end of a list. In order to do this, you’ll want to use the list’s extend() method, which takes an iterable of values, like a list, and adds them to the end of the target list.

Here you can see an example of adding a list to the end of another list using extend() .

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

>>> list_a = [1, 2, 3] >>> list_b = [4, 5, 6] >>> list_a.extend(list_b) >>> list_a [1, 2, 3, 4, 5, 6] 

Finally, to create a range and add it to the end of a list, you would do something very similar to the code above, but using the range() method instead of a predefined list:

>>> my_list = [1, 2, 3] >>> my_list.extend(range(4, 7)) >>> my_list [1, 2, 3, 4, 5, 6] 

You’ll commonly see that the return value of the range method is wrapped in a list. This is because range doesn’t actually return a list , but instead an object that implements the collections.abc.Sequence methods. While this object is iterable and list -like, it’s best practice to explicitly convert it to a list before using it.

Note that since Python lists are not typed, you can add a range to any list, regardless of what values it contains. For example:

>>> my_list = ['hello', 'world'] >>> my_list.extend(range(3)) >>> my_list ['hello', 'world', 0, 1, 2] 

Источник

Оцените статью