This question already has answers here:
Finding the index of an item in a list
(43 answers)
Closed 6 years ago.
We can access the value of a certain index in a list like so:
letters = ['a','b','c','d','e','f']
print letters[1]
The code above will print the letter 'b', because it is in the index 1 of the list, letter. So in this way, we can access a certain object in a list.
Now, if we assume that letters = ['a','b','c','d','e','f'], what code should we type to access the index of a certain object (assume it is the letter, 'c') in the list, letters?
Any and all help will be appreciated.
If letters = ['a', 'b', 'c', 'd', 'e', 'f'], the following will return the index of c in letters:
>>> letters.index('c')
2
If the value is not in the list, it will raise an error instead:
>>> letters.index('k')
valueError: 'k' is not in list
Related
This question already has answers here:
How to remove 2nd occurrence of an item in a list using remove() without removing 1st occurrence in Python
(6 answers)
Closed 3 years ago.
here I have a list, it contains many duplicate elements I want to remove the second repeated element in list how can I remove the particular element in the list?
l=["a","b","a","a","a"]
here i want to remove "a" after the second element of b(i.e a[3])
without using the index how can I remove the element in the list.
you can search the list for the index of b and then use that as the start point for searching for a's index
l=["a","b","a","a","a"]
b_index = l.index("b")
print("b index is", b_index)
first_a_after_b = l.index("a", b_index)
print("first a after b is at index", first_a_after_b)
del l[first_a_after_b]
print(l)
OUTPUT
b index is 1
first a after b is at index 2
['a', 'b', 'a', 'a']
Python list.index takes start argument which we can use to look for a's after first occurrence of b.
l = ["a","b","a","a","a"]
l.pop(l.index('a', l.index('b')+1))
# l = ['a', 'b', 'a', 'a']
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
I have the following code:
myList = ['A','B','C']
for letter in myList:
letter = myList
When running it I would expect variables to be assigned as following:
A = ['A', 'B', 'C']
B = ['A', 'B', 'C']
C = ['A', 'B', 'C']
Instead it seems that the loop is only assigning values to the "myList" component of the loop and forgetting to assign the anything for "letter". Hence the actual variable assignment looks like this:
letter = ['A', 'B', 'C']
Can someone please explain to me why python does not replace "letter" with values from "myList"?
Thank you!
It DOES replace "letter" with values from "myList": it put the value in the variable letter.
What it doesn't do is assign those values to a variable whose name is contained in letter, because that's not how assignment works
The main rule is: do not modify a list while iterating over it, but...
Given the following code to remove a specific element in a python list (but intentionally written as a loop):
mylist = ['a', 'b', 'c', 'd', 'e', 'f']
for i in mylist:
if i == 'c':
mylist.remove(i)
print(mylist)
>> ['a', 'b', 'd', 'e', 'f']
How is that the iterator does not get lost while iterating if the list is being modified inside the loop? I expected this to yield an error or an inconsistent behavior.
List iterators (other iterators may behave differently) work by remembering what index they are currently at, and when you call next it checks to see if the index is in range, and if so, gets an item and then updates the index. Your code reaches index 2, removes 'c', then goes to index 3, which is now the 'e' entry and continues on, skipping the 'd' entry completely. If you add a print statement in the for loop, you'll see the behaviour.
You can have a look at the C source code for list objects at:
https://github.com/python/cpython/blob/master/Objects/listobject.c
Look for "listiter_next" to see the implementation.
It checks if the current index is less than the length of the list:
if (it->it_index < PyList_GET_SIZE(seq))
and if it is, gets the item and increments the index:
item = PyList_GET_ITEM(seq, it->it_index);
++it->it_index;
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 5 years ago.
I'm currently doing one of the code fight's challenges, basically the challenge is to find the number of common characters between two strings. I came up with the solution below. I already passed the challenge, but I cannot figure out why I would have to iterate over the list twice and also not in every case. Thanks in advance for any explanations.
strings = [
["aabcc", "adcaa"],
["abca", "xyzbac"],
["assssbs", "aasaaaa"],
["zzzzzz", "zzz"],
["abcdefghxyzttw", "hgfedcbaabcwwt"] #<-- the strings failing with one iteration
]
def commonCharacterCount(s1, s2):
s1, s2 = sorted(list(s1)), sorted(list(s2))
matches = []
def matched(i):
matches.append(i)
s1.remove(i)
s2.remove(i)
[matched(i) for i in s1 if i in s2]
[matched(i) for i in s2 if i in s1]
[matched(i) for i in s1 if i in s2] #<-- Second for loop to find f
return len(matches)
def test():
for i in strings:
commonCharacterCount(i[0], i[1])
return
test()
You simply try this
lis=["abcdef","abcdv"]
match=[i for i in lis[0]if i in lis[1]]
It gives out put
['a', 'b', 'c', 'd']
Edit
For only one time check
>>> a
['abcc', 'abbbc']
>>> check0=list(a[0])
>>> check1=list(a[1])
>>> match=list()
>>> for i in check0:
if i in check1:
check1.remove(i)
match.append(i)
Out Put
['a', 'b', 'c']
i have the task to get the String 'AAAABBBCCDAABBB' into a list like this: ['A','B','C','D','A','B']
I am working on this for 2 hours now, and i can't get the solution. This is my code so far:
list = []
string = 'AAAABBBCCDAABBB'
i = 1
for i in string:
list.append(i)
print(list)
for element in list:
if list[element] == list[element-1]:
list.remove(list[element])
print(list)
I am a newbie to programming, and the error "TypeError: list indices must be integers or slices, not str" always shows up...
I already changed the comparison
if list[element] == list[element-1]
to
if list[element] is list[element-1]
But the error stays the same. I already googled a few times, but there were always lists which didn't need the string-format, but i need it (am i right?).
Thank you for helping!
NoAbL
First of all don't name your variables after built in python statements or data structures like list, tuple or even the name of a module you import, this also applies to files. for example naming your file socket.py and importing the socket module is definitely going to lead to an error (I'll leave you to try that out by yourself)
in your code element is a string, indexes of an iterable must be numbers not strings, so you can tell python
give me the item at position 2.
but right now you're trying to say give me the item at position A and that's not even valid in English, talk-less of a programming language.
you should use the enumerate function if you want to get indexes of an iterable as you loop through it or you could just do
for i in range(len(list))
and loop through the range of the length of the list, you don't really need the elements anyway.
Here is a simpler approach to what you want to do
s = string = 'AAAABBBCCDAABBB'
ls = []
for i in s:
if ls:
if i != ls[-1]:
ls.append(i)
else:
ls.append(i)
print(ls)
It is a different approach, but your problem can be solved using itertools.groupby as follows:
from itertools import groupby
string = 'AAAABBBCCDAABBB'
answer = [group[0] for group in groupby(string)]
print(answer)
Output
['A', 'B', 'C', 'D', 'A', 'B']
According to the documentation, groupby:
Make an iterator that returns consecutive keys and groups from the iterable
In my example we use a list comprehension to iterate over the consecutive keys and groups, and use the index 0 to extract just the key.
You can try the following code:
list = []
string = 'AAAABBBCCDAABBB'
# remove the duplicate character before append to list
prev = ''
for char in string:
if char == prev:
pass
else:
list.append(char)
prev = char
print(list)
Output:
['A', 'B', 'C', 'D', 'A', 'B']
In your loop, element is the string. You want to have the index.
Try for i, element in enumerate(list).
EDIT: i will now be the index of the element you're currently iterating through.