Getting an input as an int for a list - python

I'm trying to have the user input a vector so that it can be added, subtracted, etc. The first line is the list input, but it is storing all of the characters as strings including the brackets and commas. The third and fourth line gets rid of the brackets and commas, leaving the three user-inputted numbers as strings.
v = input('Input integers for a vector "v" ex. [1,2,-7]: ')
aux = v[1:-1]
list = aux.split(',')
for x in list:
int(x)
print(list[0] + list[1])
The for loop is my attempt to iterate the list and make all of the numbers into integers but it is still returning them as strings. For example, if I input the list [3,6,5], the program will print 36 at the end instead of the intended 9. I tried using the map function to change them, but that was returning the same values as strings.
How can I make all of the list items into integers after removing the brackets and commas?

First of all the int() caster does not cast the variable in place, it returns the casted value so you need to assign it back.
Secondly, when using the loop of the kind
for x in list:
x is not a pointer reference to the list element, instead it is variable with the value of the list element copied into it, so even if you did:
for x in list:
x = int(x)
the elements in the list will not be affected.
Your loop to convert string chars to int should be (one approach):
for i in range(len(list)):
list[i] = int(list[i])

Related

List is immutable? Cannot convert list of strings ---> list of floats

I have a list of values, titled 'list', with values 23.4158, 25.3817, 26.4629, 26.8004, 26.6582, 27.7, 27.8476, 28.025. Each value is a string, not a float. Thus, I would like to convert this to a list of floats.
When I create a for loop to reassign the strings as floats, using the float() function, within the loops it shows me that the str has been successfully converted to a float. But when I check the type outside the loop, it shows me they are still strings.
for i in list:
i = float(i)
print(i,"=", type(i))
print(type(list[0]))
HOWEVER. When I create an empty list (new_list), and append the converted floats into said list, it shows exactly what I want. In other words, the str--->float conversion is successful. Code as such:
new_list = list()
for i in list:
i = float(i)
print(i,"=", type(i))
new_list.append(i)
print(type(new_list[0]))
Why is it that the reassignment does not 'stick' unless the values are appended to new_list? Lists are mutable, so the old list should be able to be modified. Am i missing something?
The reassignment does not "stick" because you are not converting the item inside the list, you are converting i, which is another value inside the loop, completely detached from the list object. You are just converting a new variable i to float, you are not converting the item from within the list. The variable i is a new variable and python just copied the value from the item inside the new variable i. You are not converting the item from the list, you are converting a new variable i that has the same value as the item that the loop is currently at.
If you want to convert the item from withing the list using a for loop, you must target the item itself using its index:
values = [
"23.4158", "25.3817", "26.4629", "26.8004", "26.6582", "27.7", "27.8476", "28.025"
]
for i in range(len(values)):
values[i] = float(values[i])
print(values)
print(type(values[0]))
The reason why it works when appending to a list is because you are appending the newly converted i, which indeed, is a float.
I suggest reading the following:
What does Python treat as reference types?
https://www.geeksforgeeks.org/pass-by-reference-vs-value-in-python/
https://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type

How to split a string with an integer into two variables?

For example, is it possible to convert the input
x = 10hr
into something like
y = 10
z = hr
I considering slicing, but the individual parts of the string will never be of a fixed length -- for example, the base string could also be something like 365d or 9minutes.
I'm aware of split() and re.match which can separate items into a list/group based on delimitation. But I'm curious what the shortest way to split a string containing a string and an integer into two separate variables is, without having to reassign the elements of the list.
You could use list comprehension and join it as a string
x='10hr'
digits="".join([i for i in x if not i.isalpha()])
letters="".join([i for i in x if i.isalpha()])
You don't need some fancy function or regex for your use case
x = '10hr'
i=0
while x[i].isdigit():
i+=1
The solution assumes that the string is going to be in format you have mentioned: 10hr, 365d, 9minutes, etc..
Above loop will get you the first index value i for the string part
>>i
2
>>x[:i]
'10'
>>x[i:]
'hr'

List contain only one string in integer list

EDIT1:
i have problem about converting a string in a list. I collect only numbers from a file. Then convert them into integer. Using,
For line in range (0,len(file_name):
file_name[line] = int (file_name[line])
It worked, every number converted string to integer but only one number remain string. [2,4,'3']. Now, how can i convert that string into integer.
Thanks
You can do this in a list comprehension instead of a manual for loop.
file_name = [int(i) for i in file_name]

Efficient way to convert a list of one string to a string and perform split operation

I have a list which contains a string shown below. I have defined mylist in the global space as a string using "".
mylist = ""
mylist = ["1.22.43.45"]
I get an execution error stating that the split operation is not possible as it is being performed on a list rather than the string.
mylist.rsplit(".",1)[-1]
I tried to resolve it by using the following code:
str(mylist.rsplit(".",1)[-1]
Is this the best way to do it? The output I want is 45. I am splitting the string and accessing the last element. Any help is appreciated.
mylist=["1.22.43.45"]
newstring = mylist[0].rsplit(".",1)[-1]
First select the element in your list then split then choose the last element in the split
Just because you assigned mylist = "" first, doesn't mean it'll cast the list to a string. You've just reassigned the variable to point at a list instead of an empty string.
You can accomplish what you want using:
mylist = ["1.22.43.45"]
mylist[-1].rsplit('.', 1)[-1]
Which will get the last item from the list and try and perform a rsplit on it. Of course, this won't work if the list is empty, or if the last item in the list is not a string. You may want to wrap this in a try/except block to catch IndexError for example.
EDIT: Added the [-1] index to the end to grab the last list item from the split, since rsplit() returns a list, not a string. See DrBwts' answer
You can access the first element (the string, in your case) by the index operator []
mylist[0].rsplit(".", 1)[-1]

Replace item in list upon negative index as input

Currently, I have a list as such:
aList = [1,2,3,4,5]
and what I'm trying to do is to emulate 'aList[index] = item' function in python. the program prompts the user for input of negative index and the item to replace.
enter negative index: -2
enter item to replace: 7
this would give me:
[1,2,3,7,5]
since, when the index is negative, python starts counting from the back of the list. Here's my code:
aList = [1,2,3,4,5]
index = int(input("Enter index:"))
item = int(input("Enter item:"))
j = -1 #-1 means the counter should begin with -1 not 0
start = len(aList)-1 #i want python to start from the back of the list
while j<start:
if j == index:
aList[j] = item
j-=1
print(lst)
I'm getting an infinite loop because of the j-=1 and I'm wondering if I'm emulating it correctly?
I think first you need to clear you concept about array.
What is Array.?
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers1, and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Array In Python
To define a list you simply write a comma separated list of items in square brackets:
myList=[1,2,3,4,5,6]
This looks like an array because you can use "slicing" notation to pick out an individual element - indexes start from 0. For example
print myList[2]
will display the third element, i.e. the value 3 in this case. Similarly to change the third element you can assign directly to it:
myList[2]=100
The slicing notation looks like array indexing but it is a lot more flexible. For example
myList[2:5]
is a sublist from the third element to the fifth i.e. from myList[2] to myList[4]. notice that the final element specified i.e. [5] is not included in the slice.
Also notice that you can leave out either of the start and end indexes and they will be assumed to have their maximum possible value. For example
myList[5:]
is the list from List[5] to the end of the list and
myList[:5]
is the list up to and not including myList[5] and
myList[:]
is the entire list.
List slicing is more or less the same as string slicing except that you can modify a slice. For example:
myList[0:2]=[0,1]
has the same effect as
myList[0]=0
myList[1]=1
Finally is it worth knowing that the list you assign to a slice doesn't have to be the same size as the slice - it simply replaces it even if it is a different size.
I am not sure why you need a loop, when you can just access the elements by index:
aList = [1,2,3,4,5]
index = int(input("Enter index:"))
item = int(input("Enter item:"))
aList[index] = item
Of course your loop is infinite...the variable 'j' keeps getting more negative and you're comparing it so 'start', which is the length of the list minus one.

Categories