Unable to assign selected values from existing list to an empty list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Unable to assign selected values from existing list to an empty list (/thread-1654.html) |
Unable to assign selected values from existing list to an empty list - haiderhussain - Jan-18-2017 Hello experts, Python version : 2.7.10 I am using the below code for assigning the elements : a,b,c,d,e to the list : cities_list. In order to check my execution, I am using the print statement. My code : five_elements = ["a,1","b,2","c,3","d,4","e,5"] cities_list = [] for i in range(0,len(five_elements)): print(five_elements[i][0]) cities_list.append([i][0]) print(cities_list)However, I am getting different outputs : a b c d e [0, 1, 2, 3, 4]I wish to have the output as : a b c d eCould you please help me on this. Thanks, Haider RE: Unable to assign selected values from existing list to an empty list - wavic - Jan-18-2017 Hello! Every element of the list is a string which is iterable. So you just get the first element of that iterable and append it to the new list. In [1]: five_elements = ["a,1","b,2","c,3","d,4","e,5"] In [2]: cities_list = [] In [3]: for i in five_elements: ...: cities_list.append(i[0]) ...: In [4]: cities_list Out[4]: ['a', 'b', 'c', 'd', 'e']Your way: In [5]: for i in range(0,len(five_elements)): ...: cities_list.append(five_elements[i][0]) ...: In [6]: cities_list Out[6]: ['a', 'b', 'c', 'd', 'e'] RE: Unable to assign selected values from existing list to an empty list - Larz60+ - Jan-18-2017 cities_list = 'abcde' for n in range(len(cities_list)): print(cities_list[n]) RE: Unable to assign selected values from existing list to an empty list - snippsat - Jan-18-2017 Hmm what are you doing here Larz60+ range(len(something)) should never be used.We have discussed this a lot of times. The same result: cities_list = 'abcde' for n in cities_list: print(n) RE: Unable to assign selected values from existing list to an empty list - Larz60+ - Jan-18-2017 Ok .. Where did I leave my glasses RE: Unable to assign selected values from existing list to an empty list - haiderhussain - Jan-19-2017 Thanks all... |