python variable value after assignment [duplicate] - python

This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 6 years ago.
I'm new to python and in the process of rewriting an old python script and I came across the following line:
some_list = #some list with data
some_variable = [x[0] for x in some_list]
what's x[0]? I don't see x declared previously, is it being created on this line?
what would the value or some_variable be? a list?
update
by 'x' i'm referring to x[0], not the x in the for loop

In this case some_list is a list of sequences, e.g. Lists, tuples, dicts or strings. In your brackets, called a list comprehension, you iterate through some_list. x is the current element of some_list, from which you take the first element x[0] and put it in the new list.

x is the iterating element in your for-loop

Related

Single line for loop [duplicate]

This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 2 years ago.
Can someone help me rewrite this single line loop to a multiple lines for loop in python?
I am trying to understand how it is formatted.
y = {element: r for element in variables(e)}
The dictionary comprehension is equivalent to this loop:
y = {}
for element in variables(e):
y[element] = r
This is called a dict comprehension in python.
This syntax builds a dictionary by taking each element in the list variables(e) and associating it with the value r.

Change list to set without changing order of elements [duplicate]

This question already has answers here:
How do I remove duplicates from a list, while preserving order?
(30 answers)
Closed 3 years ago.
I want to remove those element from list which has repetition more than one it's like set but order should not be change
[4,6,2,6,1,2] should become [4,6,2,1]
I'am looking for any inbuilt method or list comprehension
This should do it: use lambda function and remove duplicates using set. Tested on Python 2.7
mylist = [4,6,2,6,1,2]
reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, mylist, ([], set()))[0]

How can I check if an object from one list is in another nested list? [duplicate]

This question already has answers here:
Python -Intersection of multiple lists?
(6 answers)
Closed 5 years ago.
say that I have a nested list like this for example:
List = [['a','d','b'],['a','x','w','t','d'],['g','c','d','z']]
and what I want to do is find the object in the List that all the smaller lists share, so for the example List I gave 'd' would be the object they all share.
here is what I have done so far:
def related(List):
for item in List[0]:
for i in range(1, len(List)):
if item in List[i]:
return item
the problem I am having is that when I do:
related([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
'a' is returned, but that isn't the correct answer since 'a' isn't in all the lists and only in the first 2 lists. The correct answer with that list should be 'd'.
My function basically just stops running once it finds the same object in just 1 of the lists.
Will someone be able to send me towards the right path on what I can do to get my code working correctly? Thank You!!!
What you're looking for here is the intersection of these lists. Python lists don't have an intersection functionality built-in, but sets do. We can do
def in_common(l):
if not l:
return set()
return set(l[0]).intersection(*l[1:])
This converts the first element to a set, and then finds the intersection of that set with the rest of the elements in the list.
in_common([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
returns
{'d'}
the set containing 'd'

Changing list while iterating [duplicate]

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[:]

Python - Extending a list directly results in None, why? [duplicate]

This question already has answers here:
How do I concatenate two lists in Python?
(31 answers)
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 5 months ago.
x=[1,2,3]
x.extend('a')
Output:
x is [1,2,3,'a']
But when I do the following:
[1,2,3].extend('a')
Output:
None
Why does extend work on a list reference, but not on a list?
2nd Part:
I found this because I was trying to append a listB to a listA while trying to extend listC to listB.
listA.append([listB[15:18].extend(listC[3:12])])
Supposing lists cannot be directly appended / extending. What is the most popular work around form for resolving this issue?
list.extend modifies the list in place and returns nothing, thus resulting in None. In the second case, it's a temporary list that is being extended which disappears immediately after that line, while in the first case it can be referenced via x.
to append a listB to a listA while trying to extend listC to listB.
Instead of using extend, you might want to try this:
listA.append(listB[15:18] + listC[3:12])
Or do it in multiple simple lines with extend if you want to actually modify listB or listC.
extend will extend list it self. Return type of that method is None
If you want to union 2 list and add that list to another list then you have to use another way to add.
listB[15:18] = listC[3:12]
listA.extend(listB)

Categories