What does this syntax mean in Python 3? - python-3.x

I've been seeing this syntax, but I'm not quite sure what it means. It's when two square brackets are next to the name of one list. I'm assuming this does some type of list slicing?
mylist[x][y]
mylist[][]
These are just some examples of what I've seen. (I've used variables x&y to represent an arbitrary number)

This notation can be used when the list contains some other lists as elements, which is helpful to represent the matrices. For example:
a=[[1,2,3],[4,5,6],[7,8,9]]
a[0][0] #This gives the number 1.
In this case, a[0] (the first index) chooses the 1st element, which is [1,2,3]. Then the second index (a[0][0]) chooses the first element of the list defined by a[0], thus giving the answer 1.

The top line just indexes into a list within a list. So for example, you could have
mylist = [
[1,2,3],
[4,5,6],
[7,8,9],
]
value = mylist[1][2]
which will get the value 6.
The bottom line doesn't look like valid Python to me.
EXPLANATION:
Consider that mylist[1] just extracts the second element from mylist (second because of 0-based indexing), which is [4,5,6]. Then adding [2] looks up the third item in that list, which is 6. You could also write
inner_list = mylist[1]
value = inner_list[2]
or
value = (mylist[1]) [2]
which both do the same thing.

Related

TypeError summing a list of integers

I'd like to find the sum of the elements in a list using a loop. I must be able to apply this generically if inputting different lists.
I have tried the simple
print(sum(numbers))
and it returns
TypeError: unsupported operand type(s) for +: 'int' and 'str'.
When I tried adding each individually, I found out that the list changes. The original list is [1, 3, 5, 7, 9]. When I added each element using
int(numbers[0]) + int(number[1]) # ...
when I get to index 4, there isn't a value for the index.
I'm a little unsure by what you mean, because you haven't included much code, but I believe I can answer part of it.
It's hard to know why you're having indexing errors without seeing the code you wrote, but I imagine Because you may have been removing them as you added them up.
Maybe try using an accumulator variable, which would result in python code that might look like
numbers = [1,2,3,4]
total = 0
for i in range(len(numbers)): #loops through for exactly the number of items in the list
sum = total + numbers[i]
This won't change any of the items in the list, leaving intact, and leaving you with the variable sum that is equal to the total sum of the list.

Python nested list comprehension

in my code i have created a nested list via list comprehension containing hex numbers. My next step was to calculate the decimal value of these hex numbers.
My last step was removing the () brackets of each element, because my former method created tupels for each list element.
My question here is, can i combine all three steps into one big step and if yes, will it be more efficient in computing ?
My code looks like this:
from struct import unpack
from codecs import decode
self.step1 = [[self.inputlist[self.otherlist[i]+k] for i in range(len(self.otherlist))]
for k in range(asd)]
self.step2 = [[unpack("<B",decode(x,"hex")) for x in y] for y in self.step1]
self.step3 = [[p[0] for p in q] for q in self.step2]
this code worked fine (i shortened it and am not showing how self.inputlist,otherlist,asd are defined). I am just curious if i can put self.step1, self.step2,self.step3 into one nested list comprehension.

Transform a Binary Number into a Decimal without recursivity [HASKELL]

I haven't found a way to solve this. I have a list of integer, where which element of the list is a binary digit (0 or 1) so I need to design a function which transforms this list of integers into the proper decimal number.
Example:
Input: [0,1,0]
Output: 2
But there is a specific condition, it is neccesary to use list of comprehension and you can't use recursivity.
The problem it is, when I need to know the position of the digit for apply the transform because I can't save the position in the list of comprehension.
Thank you
The problem it is, when I need to know the position of the digit for apply the transform because I can't save the position in the list of comprehension.
You can, by using zip and a range, you generate 2-tuples that carry the index, like:
[(idx, val) | (idx, val) <- zip [0..] bin]
will produce a list of 2-tuples: the first element containing the element, and the second the element of data at that position.
So if bin = [0,1,0], then the above list comprehension will result in:
Prelude> [(idx, val) | (idx, val) <- zip [0..] bin]
[(0,0),(1,1),(2,0)]
Since this seems to be the "core problem", I propose that you aim to solve the rest of the problem with the above strategy, or ask a question (edit this one, or ask a new one) if you encouter other problems.

Concatenate two integers in haskell

Hey guys I am having a problem with my code. The code below supposed to remove the first 2 in the list and then concatenate them.So the result answer would be 1,2.
first = [1,2,4,5,6,7] !! 0
second = [1,2,4,5,6,7] !! 1
newans = first ++ second
You can not remove elements from a list: Haskell is declarative meaning once you construct a list a, a will always work with the same list.
You can however construct a new list without the first two elements, and create a new list with the first two elements. For example:
get_remove_2 :: [a] -> ([a],[a])
get_remove_2 (a:b:cs) = ([a,b],cs)
We thus construct a new list with the first two elements with the [a,b] expression.
This function will take as input a list [a] and return a 2-tuple with as first element a list with two elements: the first two elements of the original list, and as second element the list where the first two elements are not present.
Note that this function will only work if the given list contains at least two elements. Otherwise it will error.

Simple adding two arrays using numpy in python?

This might be a simple question. However, I wanted to get some clarifications of how the following code works.
a = np.arange(8)
a
array([1,2,3,4,5,6,7])
Example Function = a[0:-1]+a[1:]/2.0
In the Example Function, I want to draw your attention to the plus sign between the array a[0:-1]+a[1:]. How does that work? What does that look like?
For instance, is the plus sign (addition) adding the first index of each array? (e.g 1+2) or add everything together? (e.g 1+2+2+3+3+4+4+5+5+6+6+7)
Then, I assume /2.0 is just dividing it by 2...
A numpy array uses vector algebra in that you can only add two arrays if they have the same dimensions as you are adding element by element
a = [1,2,3,4,5]
b = [1,1,1]
a+b # will throw an error
whilst
a = [1,2,3,4,5]
b = [1,1,1,1,1]
a+b # is ok
The division is also element by element.
Now to your question about the indexing
a = [1,2,3,4,5]
a[0:-1]= [1,2,3,4]
a[1:] = [2,3,4,5]
or more generally a[index_start: index_end] is inclusive at the start_index but exclusive at the end_index - unless you are given a a[start_index:]where it includes everything up to and including the last element.
My final tip is just to try and play around with the structures - there is no harm in trying different things, the computer will not explode with a wrong value here or there. Unless you trying to do so of course.
If arrays have identical shapes, they can be added:
new_array = first_array.__add__(second_array)
This simple operation adds each value from first_array to each value in second_array and puts result into new_array.

Resources