How to get a second element of every element in a list - python-3.x

Imagine a python list
a=[[1,2],[3,4],[5,6]]
how could I get a list out of this such that I get the elements of the list a that satisfy that the second element is bigger than 2?

In [32]: a=[[1,2],[3,4],[5,6]]
In [33]: [s for s in a if s[1]>2]
Out[33]: [[3, 4], [5, 6]]

So I guess the result you expect with your example is:
result=[[3,4], [5,6]]
In that case you'd just need to do:
result=[l for l in a if l[1]>2]
This is called list comprehension.

Related

Why does my_list[2, -1, -1] return an empty list?

I looked for answers but couldn't find anything.
>my_list = [7,8,9]
>my_list[2:1:-1]
[9]
>my_list[2:0:-1]
[9, 8]
>my_list[2:-1:-1]
[] # I would expect [9, 8, 7]
I am aware there are other ways to reverse a list, but I'm curious why the above doesn't work? my_list[2,None,-1] does work.
If you want to iterate from the back until the first element, leave the second element empty:
my_list[2::-1] well or write it sorter my_list[::-1]

"IndexError: list index out of range" in very simple 3 lines of Python code

I am a newbie to the programming and trying to understand how things work.
I couldn't get my program to iterate through numpy.array normally, so I decided to try one level simple iteration through list. But still it wouldn't work!
The code is as follows:
my_list = [1, 2, 3, 4, 5, 6, 7]
for i in my_list:
print(my_list[i])
The output is:
So it doesn't take the my_list[0] index of some reason and comes out of range.
Could you please help me to understand why?
It's not clear what exactly you're trying to do. When you iterate over an iterable like a list with
for i in my_list:
each i is each member of the list, not the index of the member of the list. So, in your case, if you want to print each member of the list, use
for i in my_list:
print(i)
Think about it: what if the 3rd member of the list was 9, for example? Your code would be trying to print my_list[9], which doesn't exist.
As pointed out that's not how you should iterate over the elements of the list.
But if you persist, your loop be should over the range(my_list), at the moment you're indexing by the values of the list, and since the length is 7, the last valid index is 6, not 7.
You get an IndexError, because you are looping through the values, which means, that your first value for i is 1 and the last one is 7. Because 7 is an invalid Index for this list you get an IndexError. A suitable code would be:
my_list = [1, 2, 3, 4, 5, 6, 7]
for i in my_list:
print(i)

Creating a function that shuffles a deck of cards

So the problem is as follows:
simpleSHuffle(D) takes as input list of elements. It should step through the list, at each point exchanging the current element with an element chosen at random from the remainder of the list (including the present element). In other words, if we are considering the third element of aten element list, we select an index between 3 and 9, inclusive, and exchange list[3] with list[0] before advancing to the fourth element of the list and repeating the process. Note that yo will need to use the randint() function, which has been imported for you from the random module at the top of this file
def simpleShuffle(D):
n=len(D)-1
for i in range(n):
r=randin(i,n)
temp=D[r]
D[r]=D[i]
D[i]=temp
return D
Above is what I got. Are there any other ways of doing this? Any improvements?
random.shuffle should get you what you want
>>> from random import shuffle
>>> a = [1,2,3,4]
>>> shuffle(a)
>>> a
[4, 2, 1, 3]
Note that shuffle shuffles the sequence in place and does not return anything.

Merge items from separate lists into nested lists

Hello I am trying to merge two lists sequentially into sub lists. I wonder if this is possible without list comprehensions or a lambda operation as I'm still learning how to work with those approaches. Thank you
a = [0,1,2,3]
b = [4,5,6,7]
#desired output
c = [0,4],[1,5],[2,6],[3,7]
An approach that doesn't involve lambdas or list comprehensions (not sure what the issue is with list-comps) would be with map:
c = list(map(list, zip(a, b)))
This first zips the lists together, then creates a list instance for every tuple generated from zip with map and wraps it all up in list in order for map to yield all it's contents:
print(c)
[[0, 4], [1, 5], [2, 6], [3, 7]]
This, at least in my view, is less understandable than the equivalent comprehension John supplied in a comment.
Here’s a solution suitable for beginners!
c = []
a = [0,1,2,3]
b = [4,5,6,7]
for i in range(min(len(a), len(b))):
c.append([a[i], b[i]]) # writing [a[i], b[i]] creates a new list
print(c)

how do you check if element is already in the list through comprehension?

How do you check whether an element is already in the list when I am doing it in comprehension?
For example say in following comprehension I want to restrict duplicate numbers Though I am not looking for unique number at all, I want to prevent via an if condition.
[x for x in [1,2,3,1,2,3]]
I am looking for something like
[x for x in [1,2,3,1,2,3] if not in self]
I think what you are looking for is set comprehension and conversion to list. It would do what you want without any odd syntax.
ans = list({x for x in [1,2,3,1,2,3])})
Actaully that can be also be simplified to
ans = list(set([1,2,3,1,2,3]))
but I think the first one might be better in performance.
You can't access the comprehension as you're creating it (as far as I know; someone please correct me if I'm wrong!), but in your case you can just use a set, which eliminates duplicates.
uniques = set([1, 2, 3, 1, 2, 3])
print(uniques) # >>> set([1, 2, 3])
If your list comprehension needs to be more complex, you can index the comprehension from the set, rather than the original list.
mylist = [1, 2, 3, 1, 2, 3]
print([x*x for x in set(mylist)]) # >>> [1, 4, 9]
If you really need direct access to the list during creation, you need to use an explicit loop rather than a comprehension.
x = [1,2,3,1,2,3]
y = [x[n] for n in range(len(x)) if x.index(x[n]) == n]
?
I think at this point, it's probably more readable to simply write it using a for-loop rather than a comprehension.

Resources