I am trying to check if id is in a list and append the id only if its not in the list using the below code..however I see that the id is getting appended even though id is already present in the list.. can anyone provide inputs on what is wrong here?
list = ['350882 348521 350166\r\n'] id = 348521 if id not in list: list.append(id) print list OUTPUT:- ['350882 348521 350166\r\n', 348521]
One of the best practices to do what you want to do is by using + operator. The + operator creates a new list and leaves the original list unchanged.
There are four methods to add elements to a List in Python. append(): append the object to the end of the list. insert(): inserts the object before the given index. extend(): extends the list by appending elements from the iterable.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
What you are trying to do can almost certainly be achieved with a set.
>>> x = set([1,2,3]) >>> x.add(2) >>> x set([1, 2, 3]) >>> x.add(4) >>> x.add(4) >>> x set([1, 2, 3, 4]) >>>
using a set's add method you can build your unique set of ids very quickly. Or if you already have a list
unique_ids = set(id_list)
as for getting your inputs in numeric form you can do something like
>>> ids = [int(n) for n in '350882 348521 350166\r\n'.split()] >>> ids [350882, 348521, 350166]
A more pythonic way, without using set is as follows:
lst = [1, 2, 3, 4] lst.append(3) if 3 not in lst else lst
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With