Python Forum
Alpha numeric element list search
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Alpha numeric element list search
#1
I have a list question using the following script:

list1=['a','b','c','d','e','f']
list2=['1A','1B','1C','1a','1b','1c']
list3=[]
list4=[]

for i in list1:
for j in list2:
if i in j: list3.append(j)

for i in list1:
if i not in list3: list4.append(i)

List3 correctly contains:

1a
1b
1c

But list4 contains:

a
b
c
d
e
f

However, if I use ‘if i not in str(list3): list4.append(i)’ list4 correctly lists:

d
e
f

There’s apparently something basic in lists I don’t understand. The numeral 1 seems to cause the original code to fail. For if I delete the 1’s from list2, list4 displays correctly using the original code and not str(list3).

I understand 1 is an integer, but the elements in list2 are strings. ?
Reply
#2
The elements that get displayed in list3 are '1a','1b','1c' not 'a','b','c'. Therefore, 'a','b','c','d','e','f' gets printed when you type if i not in list3. However, when you print if i not in str(list3), it looks for the elements inside the words and then prints the right answer.
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  removing one list element without using its index paul18fr 7 1,037 Feb-22-2025, 07:59 PM
Last Post: DeaD_EyE
  question about changing the string value of a list element jacksfrustration 4 2,006 Feb-08-2025, 07:43 AM
Last Post: jacksfrustration
  extract an element of a list into a string alexs 5 3,298 Aug-30-2024, 09:24 PM
Last Post: alexs
  element in list detection problem jacksfrustration 5 1,755 Apr-11-2024, 05:44 PM
Last Post: deanhystad
  Numeric Enigma Machine idev 9 2,779 Mar-29-2024, 06:15 PM
Last Post: idev
  Search Excel File with a list of values huzzug 4 2,724 Nov-03-2023, 05:35 PM
Last Post: huzzug
  list in dicitonary element problem jacksfrustration 3 1,569 Oct-14-2023, 03:37 PM
Last Post: deanhystad
  alpha advantage api question jacksfrustration 1 1,006 Oct-09-2023, 03:39 PM
Last Post: Larz60+
  search an element in pandas series learningPython 5 2,514 Apr-30-2023, 08:34 AM
Last Post: learningPython
  Find (each) element from a list in a file tester_V 3 2,160 Nov-15-2022, 08:40 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020