How to assign the value of an index of a list to a variable in Python if you only know the index number and don't know or care about the element - python-3.x

I just spent 4 hours trying to google the answer asked pretty much as above. There were 10,000 results on how to find the index of an element. But I am not interested in any of the elements and never know what they will be, how long they will be, nor what they will contain since the string is user's input.
I have studied the Python manual for "lists" and tried several methods. I used loops of several types. List comprehensions were simply too complicated for my tiny brain although I tried. In fact, I tried for 4 hours googling and tweaking things maybe a hundred times but I only received errors after error of every type which I chased down one by one. I am not providing any code because I am not interested in having anyone fix it (its for an online course and that would be cheating). I just want to know the syntax for one little thing that is preventing me from making it work.
I need to assign the position of any element (i.e., the index integer value) anywhere in the list to a variable so I can control some boundaries. The most important thing for me is to set some conditions for the first character of the string converted to a list.
I was not very clear explaining what I am trying to do so I edited to add this:
pseudo code:
1. Ask the user for input and assign it a variable
2 Convert the string into a list where each letter of the string is an element of the list.
#The operation is dependent only on the position and not on the content of each character in the list.
3 For some elements of the list (but not all of them, which is why a loop won't work) perform an operation depending on their position (or index value)in the list.
in other words:"if the element is in position 0 of the list (or 3 or 27 etc) of the list then do something to the element." And I won't know or care what the content of the original element was.
If I know how to do that then I can extrapolate it for other character positions in the list.
I am an total beginner, and am not familiar with technical jargon, so please provide the simplest, least complex method! :-) Thank you in advance.

I'm an amateur myself but I will take a shot. If you can please do share some more context and some code for clarity.
I just checked the comment you made 50 mins ago. If I understand correctly, you want to assign the indexes to a variable. If that's correct can use the enumerate function. It's a built-in function for sequences. If we were to apply enumerate on our list named text it will return the position e.g. the index and the value of that position.
text = ["B", "O", "O", "M"]
for index, value in enumerate(text):
print(index, value)
This code will give you the following result:
0 B
1 O
2 O
3 M
Inside the for loop, you have the index variable that will now refer to the position of each value. You can now apply further conditions, like if index == 0:... and do your thing.
Does this help?

I also tried this one:
I think this is what you want. It assigns the value of an index (0,1,2,3) of a list to a variable.
list = ["item 1", "item 2", "item 3"]
item = input("Enter some text: ")
if item == list[0]:
index = 0
elif item == list[1]:
index = 1
elif item == list[2]:
index = 2
print(index)

I tried this because you said: "if this is index 0 of the list then do this"
It checks if the value of the input is the item with index 0 of the list.
list = ["item 1", "item 2", "item 3"]
item = input("Enter some text: ")
if item == list[0]:
print("This is index 0 of the list")
else:
print("This is not index 0 of the list")
If this is not the thing you're looking for, could you please try to explain it in a different way? Or maybe try writting some code too please.

Related

Python ord() and chr()

I have:
txt = input('What is your sentence? ')
list = [0]*128
for x in txt:
list[ord(x)] += 1
for x in list:
if x >= 1:
print(chr(list.index(x)) * x)
As per my understanding this should just output every letter in a sentence like:
))
111
3333
etc.
For the string "aB)a2a2a2)" the output is correct:
))
222
B
aaaa
For the string "aB)a2a2a2" the output is wrong:
)
222
)
aaaa
I feel like all my bases are covered but I'm not sure what's wrong with this code.
When you do list.index(x), you're searching the list for the first index that value appears. That's not actually what you want though, you want the specific index of the value you just read, even if the same value occurs somewhere else earlier in the list too.
The best way to get indexes along side values from a sequence is with enuemerate:
for i, x in enumerate(list):
if x >= 1:
print(chr(i) * x)
That should get you the output you want, but there are several other things that would make your code easier to read and understand. First of all, using list as a variable name is a very bad idea, as that will shadow the builtin list type's name in your namespace. That makes it very confusing for anyone reading your code, and you even confuse yourself if you want to use the normal list for some purpose and don't remember you've already used it for a variable of your own.
The other issue is also about variable names, but it's a bit more subtle. Your two loops both use a loop variable named x, but the meaning of the value is different each time. The first loop is over the characters in the input string, while the latter loop is over the counts of each character. Using meaningful variables would make things a lot clearer.
Here's a combination of all my suggested fixes together:
text = input('What is your sentence? ')
counts = [0]*128
for character in text:
counts[ord(character)] += 1
for index, count in enumerate(counts):
if count >= 1:
print(chr(index) * count)

Is there a way to get increment counter from a Python 'for' loop with decrement range?

I read everyone uses enumerate, but I don't think I know how to use it in my code. I want to print the value of an alphabet in a string according to alphabet order and the next character will increment the value by 1 and I want to start it from the last character in the string.
I can solve the code, but how can I replace the counter i without using i = i+1 to make this code a bit shorter? Is there a way to implement something in the for loop?
This is my code:
def project(r):
i = 0
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+i)
i=i+1
project(str(input()).lower())
For example, if I insert a string such as "sad", the output will be [4,2,21] because d = 4, a = 1, s = 19.
Is there a way to implement the counter without initializing i?
According to your question what I can understand is you want to use enumerate to get your result.
You can simply do as below:
def project(r):
for (i, char) in enumerate(r, 0):
print(ord(r[-i-1])-96+i)
project(str(input()).lower())
And the enumerate() method adds a counter to an iterable and returns it in a form of an enumerate object.
Syntax: enumerate(iterable, start)
Here 0 is the default value of start which you can give according to your requirement. For example, if you want your counter to start from 100, then you can do like enumerate(iterable, 100).
In the above code, I have used enumerate() function and initialized the counter from 0 and as you want to display from the last, I used -ve index to get the last item in a list.
And as I initialized the counter 0 so how can I get the items from last? For that, I subtract the index by -1 like r[-i-1]. So for the first iteration the i value becomes 0, so r[-i-1] becomes r[-0-1] which is r[-1] and on the second iteration, i becomes 1, so r[-i-1] becomes r[-1-1]which isr[-2]` which result second last item. Similarly it goes on.
For more information about enumeration, please check the below link so you can get a clear idea.
Python enumerate()
13. Enumerate
Dcoder14, actually I want to make my code a bit shorter. Even there is a way other than enumerate, but still thank you very much... I used your code, but I edited it a little bit to make it one line shorter...
This is my code:
def project(r):
for (i, char) in enumerate(r, 0):
print(str(ord(r[-i-1])-96+i))
project(str(input()).lower())
If you want to make it shorter, you can use the decrement char value since we can get an increment by subtracting the length of the string (input) with char in the for loop.
For example, this is my code:
def project(r):
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+(len(r)-char))
project(str(input()).lower())

Why is this iteration not updating the count?

I am writing a function that takes two strings as parameters, turns them in lists, and then returns an index of where the two strings differ:
def ss(line1,line2):
count = 0
list1 = line1.split()
list2 = line2.split()
for word in list1:
if word is not list2[count]:
return count
else:
count += 1
ss("Why is this not working?", "Why is this not working?")
The output I get is that my count is whatever I set it to initially (e.g., "0"). As far as I can see, it should be updating the count and then reiterating through the lists to compare the next indexes?
What do I not understand about how for-loops work?
Thanks.
The issue is that you are using != instead of is not.
Explanation:
The is keyword in Python compares object identity. Every string in Python is it's own separate object and thus, it's own separate identity. So when you use the is keyword with two strings it will not check the actual contents.
However, to compare the contents of an object or variable you can use == or != which return True or False.
I hope this answer helped you and if you have any further questions please feel free to post a comment below!

Finding position of first letter in subtring in list of strings (Python 3)

I have a list of strings, and I'm trying to find the position of the first letter of the substring I am searching for in the list of strings. I'm using the find() method to do this, however when I try to print the position of the first letter Python returns the correct position but then throws a -1 after it, like it couldn't find the substring, but only after it could find it. I want to know how to return the position of the first letter of he substring without returning a -1 after the correct value.
Here is my code:
mylist = ["blasdactiverehu", "sdfsfgiuyremdn"]
word = "active"
if any(word in x for x in mylist) == True:
for x in mylist:
position = x.find(word)
print(position)
The output is:
5
-1
I expected the output to just be:
5
I think it may be related to the fact the loop is searching for the substring for every string in the list and after it's found the position it still searches for more but of course returns an error as there is only one occurrence of the substring "active", however I'm not sure how to stop searching after successfully finding one substring. Any help is appreciated, thank you.
Indeed your code will not work as you want it to, since given that any of the words contain the substring, it will do the check for each and every one of them.
A good way to avoid that is using a generator. More specifically, next()
default_val = '-1'
position = next((x.find(word) for x in mylist if word in x), default_val)
print(position)
It will simply give you the position of the substring "word" for the first string "x" that will qualify for the condition if word in x, in the list 'mylist'.
By the way, no need to check for == True when using any(), it already returns True/False, so you can simply do if any(): ...

Trying to understand a Python line code

I am new to python, and when I search for a way to get a string length without using "len()", I found this answer:
sum([1 for _ in "your string goes here"])
Can someone help me understand this line,what's the '1' doing there for example?
This is basically equivalent to this:
lst = []
for dontCareAboutTheName in "your string goes here":
lst.append(1)
print(sum(lst))
The list comprehension basically collects the number 1 for each character it finds while looping through the string. So the list will contain exactly as many elements as the length of the string. And since all those list elements are 1, when calculating the sum of all those elements, you end up with the length of the string.

Resources