python extract variable from a list - python

I'm pretty new to python and I'm stacked on a simple problem:
i have a list:
mylist = [1, 2, 3, 4]
if I extract one element like this:
print(my_list[1:2])
I get a list of one element, but i cannot compute any calculus by treating it as a variable :
print(my_list[1:2]+1)
because i get the error:
Traceback (most recent call last):
File "C:\...\test_tuple.py", line XX, in <module>
print(my_list[1:2]+1)
TypeError: can only concatenate list (not "int") to list
how do I convert this single element list to a variable?

What you are doing, with :, is slicing. This means grabbing a piece of a list as a new list. What you want is just one index, which you can do be using:
mylist = [1, 2, 3, 4]
print(mylist[2]+1)
You can also turn a one element list into a variable by using:
mylist = [1, 2, 3, 4]
new_list = mylist[1:2]
print(new_list[0]+1)
Lastly you can also use numpy arrays on which you can perform calculations as if it were a normal number as follows:
import numpy as np
mylist = [1, 2, 3, 4]
new_arr = np.array(mylist[1:2])
print(new_arr[0]+1)
of course the first solution is the best in this case, but sometimes other solutions can fit your problem better.

You're error is about, you are adding number to [],
you need to add number to number like below code;
print(my_list[1:2+1])
print(my_list[2+1])
print(my_list[2]+1) ##here youre adding to the value like (my_list[2])3+1 that it will not give you error

Related

Creating new indexin in list python

In Python, if I want to add one element like below, what do I need to do (without using build-in-function)?
a = [0,1,2,3]
a[3+1]=4
print(a)
Traceback (most recent call last):
File "/home/cyber/Program/Python/Design Thinking/Python code/q2.py", line 18, in <module>
a[3+1]=4
IndexError: list assignment index out of range
Looks like you want to add the value 4 to the end of list a in which case:
a = [0,1,2,3]
a += [4]
print(a)
Output:
[0, 1, 2, 3, 4]
However, if you want to add a value at, say, index 5 then you can't do that without extending the list to accommodate that index and any missing ones. What are known in other languages as sparse lists (arrays) don't exist in Python. Of course you could write something yourself

How can I convert a list of values into an index/slice from a list?

I have a list that contains many elements, where each element represents an input file, that I want to dynamically subset using the values contained within another list. For example, I have some code that dynamically generates lists that I want to use to define the sub-samples such as
[0, 1, 2, 3]
and
[1, 2, 3, 4]
But I want to use the start and end elements of each of these lists to define an slice range to be applied to another list. In other words, I want the two above lists to be converted into slices that look like this
[0:3]
and [1:4]
But I don't know how to do this, and to be honest I'm not even sure the correct terminology to use to search for this. I have tried searching stack overflow for 'dynamically generate slices from lists' or even 'dynamically generate data slice' (an variants that I can think of along those lines) without any success.
Here are a few more details:
thislist = ['2019/12/26/fjjd', '2019/12/26/defg', '2020/01/09/qpfd', '2020/01/09/tosf', '2020/01/16/zpqr', '2020/01/15/zpqr', '2020/01/15/juwi']
where someIndexSlice is
[0:3]
and generated from a list that looks like this
[0,1,2,3]
thislist[someIndexSlice] = ['2019/12/26/fjjd', '2019/12/26/defg', '2020/01/09/qpfd', '2020/01/09/tosf']
So my questions are:
How can I accomplish this?
What sort of terminology should I use to describe what I am trying to accomplish?
Thanks
You can use the built-in slice function:
>>> lst = [0, 1, 2, 3]
>>> as_slice = slice(lst[0], lst[-1], lst[1] - lst[0])
>>> as_slice
slice(0, 3, 1) # which is same as [0:3]
And then to check if it works correctly:
>>> test = [1, 5, 3, 7, 8]
>>> test[as_slice]
[1, 5, 3]
>>> test[0:3]
[1, 5, 3]
NOTE:
This implementation assumed your lists are equidistant, and sorted.

What's the Pythonic way to initialize an array?

I often see arrays in Python 3 that are declared in either one of two ways:
foo[2, 2] = [[1, 2], [3, 4]]
or...
foo[2][2] = [[1, 2], [3, 4]]
I've tried using both of these in computationally-expensive tasks(i.e. Machine Learning) for gargantuan arrays, and they seem to have not much of a difference.
Is there a difference between the two, in terms of memory allocation and execution times for looping and such, when the lists are big?
In this case it creates the tuple (ti, tj) and passes it to dense.__getitem__(). As to what that accomplishes, you will need to see the documentation and/or source for dense's type.
The code dense[ti, tj] calls dense.__getitem__((ti, tj)). The comma in this case constructs a tuple. This doesn't work with lists, but it could work with a dictionary if the keys are tuples.
>>> [1,2,3][1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
>>> {(1, 2): 1}[1, 2]
1

List of lists based on numbers in another list

Let's say I have an array
a = np.array[5, 3, 2]
and based on that array I want to return a new array in the form:
b = np.array[ [0, 1, 2, 3, 4], [0, 1, 2], [0, 1] ]
I've been trying:
for item in a:
b = np.hstack(np.arange(item))
print b
but this only gives me the elements without joining them into an array;
for item in a:
b = b.append((b[:], b[item]))
print b
but this approach blows up nicely with a:
AttributeError: 'numpy.ndarray' object has no attribute 'append'
I have tried other things, like:
b[item] = np.arange(item),
but that one complains about out-of-bounds indices.
And
b = np.zeros(len(a))
for item in np.arange(len(a)):
b[item] = np.arange(b[item])
print b
which complains with
ValueError: setting an array element with a sequence.
That last one is the one that looks more promising and, searching for some questions on this site (https://stackoverflow.com/a/13311979/531687) I know that the problem is that I am trying to fit a sequence where a value is expected, but I can't figure out my way around it.
How can I go about this?
This should work
b = [range(x) for x in a]
update
The brackets [...] here create a list and inside an iterator can be used to define the items in the list. In this case the items of of type range(x) for each item in a.
Note that there is a difference in implementation between python2 and python3 here. In python2 this actually generates a list of lists. In python3 however this generates a lists of generators (the python2 equivalent would be xrange), which is typically more efficient.

Appending two arrays together in Python

I've been working in Python with an array which contains a one-dimensional list of values. I have until now been using the array.append(value) function to add values to the array one at a time.
Now, I would like to add all the values from another array to the main array instead. In other words I don't want to add single values one at a time. The secondary array collects ten values, and when these are collected, they are all transfered to the main array. The problem is, I can't simply use the code 'array.append(other_array)', as I get the following error:
unsupported operand type(s) for +: 'int' and 'list'
Where am I going wrong?
Lists can be added together:
>>> a = [1,2,3,4]
>>> b = [5,6,7,8]
>>> a+b
[1, 2, 3, 4, 5, 6, 7, 8]
and one can be easily added to the end of another:
>>> a += b
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
You are looking for array.extend() method. append() only appends a single element to the array.
Array (as in numpy.array or array module) or list? Because given your error message, it seems the later.
Anyway, you can use the += operator, that should be overridden for most container types, but the operands must be of the same (compound) type.
Usually, if you want to expand a structure to the right (axis=1) or at the bottom (axis=0), you should have a look at the numpy.concatenate() function, see Concatenate a NumPy array to another NumPy array.
np.concatenate(arr1, arr2, axis=0)
is probably what is needed here, adding a new row in a nested array.

Categories

Resources