This question already has answers here:
How to access List elements
(5 answers)
Closed 5 years ago.
I am working with a list of lists longitudes and latitudes. Each inner list has an extra pair or square brackets.
For instance:
[[-87.77621462941525,-87.77676645562643,-87.77906119123564]]
I would like to remove the extra brackets and be left with:
[-87.77621462941525,-87.77676645562643,-87.77906119123564]
Thanks
this is nested list object, you can access the inner list with index.
In [1]: l = [[-87.77621462941525,-87.77676645562643,-87.77906119123564,]]
In [2]: l[0]
Out[2]: [-87.77621462941525, -87.77676645562643, -87.77906119123564]
List Indexing
You can simply use list indexing.
my_lists = [[-87.77621462941525,-87.77676645562643,-87.77906119123564,]]
my_list = my_lists[0]
next
Another way of doing this is using next which takes an iterable as an argument. It will raise a StopIteration in the case of the iterable being empty. You can prevent this by adding a default value as a second argument.
my_list = next(iter(my_lists))
Or
my_list = next(iter(my_list), []) # Using [] here but the second argument can be anything, really
Obviously this second option might be a bit of overkill for your case but I find it a useful one-liner in many cases. For example:
next_element = next(iter(list_of_unknown_size), None)
Versus
next_element = list_of_unknown_size[0] if list_of_unknown_size else None
Related
This question already has answers here:
Appending item to lists within a list comprehension
(7 answers)
Closed 2 years ago.
I'm trying to iterate through a list and generate another list. is this achievable using list comprehension?
source = ['1/2','1/3','1/4']
port_hdl_dict = {'1/2':'1/1/2','1/3':'1/1/3','1/4':'1/1/4','1/5':'1/1/5'}
def getSourcePortlistIxia(source_list,port_hdl_dict):
source_port_list = []
for i in source_list:
source_port_list.append(port_hdl_dict[i])
return(source_port_list)
res = getSourcePortlistIxia(source,port_hdl_dict)
print(res)
This i tried to acheive this using liist comprehension
source_port_list = []
my_list = [source_port_list.append(port_hdl_dict[i]) for i in source]
print(my_list)
but this prints the output as
['1/1/2', '1/1/3', '1/1/4']
[None, None, None]
am I doing anything wrong here? how do we achieve this?
my_list = [port_hdl_dict.get(v) for v in source]
Generating a list, or another iterable structure from a list is one of the best use cases for list comprehension. The problem with your code is that the append operation doesn't return anything. Because that's what you're storing inside my_list, when you print my_list, you get [None, None, None]
Furthermore, it seems to me that what you're actually trying to do is get all values from a dictionary, for a given set of keys.
You can achieve that by, instead of using a third list that you append to, returning the value in the dictionary, inside the list comprehension, as such:
my_list = [port_hdl_dict[i] for i in source]
The above is a very naive example with no validation. So, for example, if i was not a valid key inside port_hdl_dict, then your code would raise an exception.
You can add some simple validation by simply checking i is in port_hdl_dict
my_list = [port_hdl_dict[i] for i in source if i in port_hdl_dict]
This question already has answers here:
Modifying a list while iterating over it - why not? [duplicate]
(4 answers)
Closed 6 years ago.
I've found a python puzzle and can't find out why it works.
x = ['a','b','c']
for m in x:
x.remove(m)
and after this loop x = ['b'].
But why?
As far as I understand for keyword implicitly creates iterator for this list. Does .remove() calls __next__() method so b is skipped? I can't find any mentions of it but this is my best guess.
Here you are iterating over the original list. On the first iteration, you removed the 0th index element i.e. a. Now, your list is as: ['b','c']. On the second iteration your for loop will access the value at index 1 but your index 1 has value c. So the c is removed. Hence resultant list will be ['b'].
In order to make it behave expectedly, iterate over the copy of the list, and remove the item from original list. For example:
x = ['a','b','c']
for m in list(x): # <-- Here 'list(x)' will create the copy of list 'x'
# for will iterate over the copy
x.remove(m)
# updated value of 'x' will be: []
Note: If it is not for demo purpose and you are using this code for emptying the list, efficient way of emptying the list will be:
del x[:]
This question already has answers here:
python - get list of tuples first index?
(5 answers)
Closed 6 years ago.
I have a list of tuples in this format:
my_list = [(1,4),(3,6),(10,7)]
I want to print the second elements of each tupple:
4,6,7
I can access those values as:
my_list[0][1]
my_list[1][1]
my_list[2][1]
But that isn't a reasonable approach for any reasonable size list, for now, and doing using list comprehension:
[x[1] for x in my_list ]
Is there any solution that doesn't imply to use a loop?
something like:
my_list[:][1]
I tried to do it that way but got:
(3, 6)
[:] just creates a copy of the list, so [1] indexes that copy. And no, outside of NumPy arrays, there is technically no way to avoid a loop. The loop may be done in C code in a function like map(), but there's going to be a loop anyway.
Using map() for example applies a callable for each element in your input list:
map(lambda nested: nested[1], my_list)
or
from operator import itemgetter
map(itemgetter(1), my_list)
Both work in Python 2, in Python 3 you need to wrap the map() call in a list() call to drive the iteration.
Either way, I find a list comprehension to be clearer here anyway.
As mentioned in python get list of tuples first index
try with zip
my_list = [(1,4),(3,6),(10,7)]
print zip(*my_list)[1]
(4, 6, 7)
This question already has answers here:
Finding the index of an item in a list
(43 answers)
Closed 9 years ago.
I am trying to figure out how to determine if a tuple has an exact match in a list of tuples, and if so, return the index of the matching tuple. For instance if I have:
TupList = [('ABC D','235'),('EFG H','462')]
I would like to be able to take any tuple ('XXXX','YYYY') and see if it has an exact match in TupList and if so, what its index is. So for example, if the tuple ('XXXX','YYYY') = (u'EFG H',u'462') exactly, then the code will return 1.
I also don't want to allow tuples like ('EFG', '462') (basically any substring of either tuple element) to match.
Use list.index:
>>> TupList = [('ABC D','235'),('EFG H','462')]
>>> TupList.index((u'EFG H',u'462'))
1
I think you can do it by this
TupList = [('ABC D','235'),('EFG H','462')]
if ('ABC D','235') in TupList:
print TupList.index(i)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python list confusion
When I write a simple python script, I define a new list as follows:
A=[[],]*10
What I wanna do is just initialize a list whose length is 10 and each element is a empty list.
And when I do something like:
A[0].append(["abc",])
I just wanna append this ["abc",] to A[0], and it turn out to be that every elements in A is appended with ["abc",]
I know this probably due to my initialization (A=[[],]*10) . I just want to know why this happened.
Your expression A=[[]]*10 is equivalent to:
a = []
A = [a]*10
This means that A consists of 10 references to one and the same list.
You are creating a list with 10 references to the same empty list.
You should use a list comprehension instead:
A = [[] for _ in range(10)]
In a list comprehension, you create a new list for every iteration through the loop. If you are using python 2, you should use xrange instead of range (although with only 10 elements that won't make much difference).
All the empty lists are references to the same object.