-2

I've the following code:

characters = ['a', 'b', 'b', 'c','d', 'b']

for i in characters:
    if i[0] == i[-1]:
        print(i)

Basically I only want to extract the characters that are equal from the line above. For example, in my case I only want to extract the b from 1 and 2 position.

How can I do that?

Thanks!

Nihal
  • 5,262
  • 7
  • 23
  • 41
Pedro Alves
  • 1,004
  • 1
  • 21
  • 47

5 Answers5

1
a = ['a', 'b', 'b', 'c', 'd', 'b']
b = ['a', 'b', 'b', 'c', 'd', 'b', 'd']

import collections

print([item for item, count in collections.Counter(a).items() if count > 1])
print([item for item, count in collections.Counter(b).items() if count > 1])

output

['b']
['b', 'd']
Nihal
  • 5,262
  • 7
  • 23
  • 41
  • he wants the one that is equal to the last one not the ones repeated, how could someone upvote this? – E.Serra Sep 18 '18 at 10:46
1

Without iterating multiple times over the same list.

characters = ['a', 'b', 'b', 'c','d', 'b']
last_char = None

output = []

for char in characters:
    if char == last_char:
        output.append(char)
    last_char = char

print(output)
Tom Wojcik
  • 5,471
  • 4
  • 32
  • 44
0

To extract the characters form the list which matches only the last char from list you can do the following:

characters = ['a', 'b', 'b', 'c','d', 'b']

for i in range(0, len(characters) - 1):
    if characters[i] == characters[-1]:
        print(characters[i])

In you snippet i when you are looping is the individual chars from your list, and it looks you were trying to access last, and first item from the list.

Nihal
  • 5,262
  • 7
  • 23
  • 41
warl0ck
  • 3,356
  • 4
  • 27
  • 57
0
equal = [a for a in characters[0:-1] if a == characters[-1]]

Unless you also want the last character which will always be equal to itself, then do:

equal = [a for a in characters if a == characters[-1]]
E.Serra
  • 1,495
  • 11
  • 14
0

little modification in your code

characters = ['a', 'b', 'b', 'c','d', 'b']
ch=  (characters[-1])
for i in characters:
    if i == ch:
        print(i
Roshan Bagdiya
  • 2,048
  • 21
  • 41