Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending an id to a list if not already present in a string

Tags:

python

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] 
like image 946
user2341103 Avatar asked Jun 28 '13 18:06

user2341103


People also ask

How do I add an item to a list without adding an append?

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.

Can you append an object to a list?

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.

Can you append a list to a string in Python?

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.


2 Answers

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] 
like image 105
John Avatar answered Oct 10 '22 03:10

John


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 
like image 20
Atihska Avatar answered Oct 10 '22 02:10

Atihska