I have a list:
listA = ['1,2,3,4,5']
where it is in string format. I want to perform a simple function that removes the last digit in the string, which in this case would be 5 and print it out.
I've tried something
listA = ['1,2,3,4,5']
for i in listA:
print(listA.pop())
What i tried is wrong as I'm not familiar with using pop on strings.
What you have is not a list of integers. It is a list with a single element, that element is a string of comma separated integers
You're not using i
You're iterating over the list and mutating it as you do so. Do not do this, because it does not give you the behaviour you expect.
I would recommend a while loop instead. First, fix your array.
listA = listA[0].split(',')
Now, iterate over it.
while listA:
print(listA.pop())
You use the truthiness of a nonempty list to keep iterating over it. This removes all the digits. However, if you just want the last digit and nothing more, call listA.pop() only once.
If you don't want to fix your array, you should extract the last digit like this:
listA = ['1,2,3,4,5']
print(int(listA[0][-1])) # [0] gets the string, [-1] gets the last character in the string
This is ungainly, so I recommend fixing your array instead.
The previous answer is giving you the last character. You can also extract the last value using split which will break up text based on a defined delimiter:
listA = ['1,2,3,4,5']
print( listA[0].split(',')[-1] )
Related
From a python function, I get the following output:
['(0.412169, mississippi)']
The type indicates that it is a list. I want to extract the values from the list and save it as separate elements. I tried various functions to convert list to tuple, list to str, extracting the element by Index from the tuple or str, nothing worked out. When I try to extract the element by index, I either get '(' for the first element index 0, or when I try to extract through a iterator function, I get all the values split up like the full data set as a string.
How do I get values separately.
You can iterate over your data, remove the parentheses using slicing and split the string by comma to create a list, which will be appended to your output payload:
data = ['(0.412169, mississippi)', '(0.412180, NY)']
extracted_values = []
for d in data:
extracted_values += d[1:-1].split(",")
print(extracted_values)
# output: ['0.412169', ' mississippi', '0.412180', ' NY']
Your list content a string, not a list.
If you want to extract the content of a string, use the "eval" statement
my_tuple = eval("(0.412169, 'mississippi')")
Note that the "eval" function can be dangerous, because if your string content python code, it could be executed.
I am new to this sort of stuff, so sorry if it's really simple and I am just being stupid.
So I have this variable with some bytes in it (not sure if that's the right name.)
data = b'red\x00XY\x001\x00168.93\x00859.07\x00'
I need to convert this to a list. The intended output would be something like.
["red","XY","1","169.93","859.07"]
How would I go about doing this?
Thank you for your help.
We can use the following line:
[x.decode("utf8") for x in data.split(b"\x00") if len(x)]
Going part by part:
x.decode("utf8"): x will be a bytes string, so we need to convert it into a string via `.decode("utf8").
for x in data.split(b"\x00"): We can use python's built in bytes.split method in order to split the byte string by the nullbytes to get an array of individual strings.
if len(x): This is equivalent to if len(x) > 0, since we want to discard the empty string at the end.
This code may help you to understand if you want exact same output using the pop() function.
data = 'red/x00XY/x001/x00168.93/x00859.07/x00' # I change "/" mark from "\" because i'm using Linux otherwise it will give error in Linux
new_list = [] # There is a variable that contain empty list
for item in data.split('/x00'): # Here I use split function by default it splits variable where "," appears but in this case
new_list.append(item) # you need list should be separated by "/" so that's why I gave split('/x00') and one by list appended
print(new_list)
Write a function that takes, as an argument, a list, identified by the variable aList. If the list only contains elements containing digits (either as strings as integers), return the string formed by concatenating all of the elements in the list (see the example that follows). Otherwise, return a string indicating the length of the list, as specified in the examples that follow.
I am just starting to learn how to code and this is my first CS class.
def amIDigits(aList):
for element in range(aList):
if element in aList.isdigit():
bList=[]
bList.append(aList)
return str(bList)
amIDigits([“hello”, 23]) should return the string “The length of the input is 2.”
amIDigits ([“10”, “111”]) should return the string “10111”
If I understand it right the output will be the joined digits even if they are not of the string format. So the best way is to use the all function (returns true if all elements of an iteration are true) and check if the string elements of the list are digits. If so, then return the join of all elements of the list converted to a string. Else, we return the length of the list using the new string formatting syntax (f represents string formatting and the {} return the result of an operation).
code:
def amIDigits(aList):
if all([str(i).isdigit() for i in aList]):
return ''.join(map(str,aList))
else:
return f'The length of the input is {len(aList)}.'
print(amIDigits(['hello', 23]))
print(amIDigits(['10', '111']))
print(amIDigits([55, 33]))
output:
The length of the input is 2.
10111
5533
First, I highly recommend having someone literally sit down and have you walk them through your thought process. It is more useful as a learner to debug your thought process than to have someone give you the answer.
One thing I noticed is that you created your empty list, bList, inside the for block. This will not work. You need to create an empty list to store things into before you begin for looping through the old list, otherwise you will be over-writing your new list every time it loops. So right now, your bList.append() statement is appending an element onto an empty list every time it runs. (You will get only the very last element in the aList stored into your bList.)
Another problem is that you use the range() function, but you don't need to. You want to look at each element inside the list. Range creates a sequence of numbers from 0 to whatever number is inside the parentheses: range() documentation. Your code tries to pass a list into range(), so it is invalid.
The "for blank in blank" statement breaks up whatever list is in the second blank and goes through each of its elements one at a time. For the duration of the for statement, the first blank is the name of the variable that refers to the element being looked at. so for example:
apples = ["Granny Smith","Red Delicious","Green"]
for apple in apples:
eat(apple) #yum!
The for in statement is more naturally spoken as "for each blank in blank:"
I just want to ask if how should I pop certain elements inside the list.
Let's say I have this list:
c = ['123','456','789']
When I type this:
print c[0][0]
It prints a value '1',
And somehow I want to delete the first element of the first value.
So that the output will be:
c = ['23','456','789']
But I have a problem in using pop().
I tried this but no luck:
c.pop(0, 0) # takes only one argument
Or
c[0].pop(0) # string doesn't have an attribute pop
Is there a way to solve my dilemma?
If this problem has a duplicate, please let me know.
Strings are immutable. As such, they can't be modified once created.
If all you want to do is "remove" the first character of the first string in the list c you can use slicing (that returns a new string):
c[0] = c[0][1:]
Read more on slicing here: Explain Python's slice notation
Im pretty new to Python.
I have a list which looks like the following:
list = [('foo,bar,bash',)]
I grabbed it from and sql table (someone created the most rubbish sql table!), and I cant adjust it. This is literally the only format I can pull it in. I need to chop it up. I can't split it by index:
print list[0]
because that just literally gives me:
[('foo,bar,bash',)]
How can I split this up? I want to split it up and write it into another list.
Thank you.
list = [('foo,bar,bash',)] is a list which contains a tuple with 1 element. You should also use a different variable name instead of list because list is a python built in.
You can split that one element using split:
lst = [('foo,bar,bash',)]
print lst[0][0].split(',')
Output:
['foo', 'bar', 'bash']
If the tuple contains more than one element, you can loop through it:
lst = [('foo,bar,bash','1,2,3')]
for i in lst[0]:
print i.split(',')