When I was watching videos about introduction to lists for Python I encountered this code:
b = ["banana", "apple", "Microsoft"]
print(b)
(when i print this)
'banana','apple','Microsoft'
I was told to swap the first element and the third element using their index. The working solution that they gave me was this:
b[0], b[2] = b[2], b[0]
print(b)
(when i print this):
'Microsoft','apple','banana'
which was correct. However, I don't understand how the code works, so can anyone please explain?
In most other languages, you would need to create a temporary variable and then switch them over. In Python, this would look like:
a = 1
b = 2
temp = a
a = b
b = temp
Python allows you to swap these in one line.
a = 1
b = 2
a, b = b, a
Now, b = 1 and a = 2
The [brackets] at the end of the variable references the position within the list.
Related
I'm fairly new to coding. I'm trying to iterate the variable k through my function and store the results in a list. k starts with k=1 and ends with k=40. But something isnt working. My list only contains 0s. Hopefully you can help me
Here is a Screenshot of my code
Here is another attempt
Tn = []
for k in range(1, 40):
x = ((40+0.2) / ((k-0.4))* (17/40))
Tn.append(x)
print Tn
Your k variable is a range object, not an index.
Try putting your variable inside a list, and then iterate through that list. You don't even have to use the range object to iterate through a list :
lst = [10, 20, 30, 40]
for item in lst:
print(item) # print item if you use Python 2
And if you want to use an index :
for index in range(len(lst)):
print(lst[index]) # print lst[index] if you use Python 2
If you want to use variables :
a = 10
b = 20
c = 30
d = 40
lst = [a, b, c, d]
for item in lst:
print(item) # print item if you use Python 2
Side note : you seem to be using Python 2. I would highly recommend you use Python 3.x (the latest the version the better). The transition is not difficult at all, and even easier if you're new to coding. Python 3.x has way more to offer than Python 2 and you will quickly see its limitations.
This question already has an answer here:
How does swapping of members in tuples (a,b)=(b,a) work internally?
(1 answer)
Closed 1 year ago.
If we need to swap variables a and b in C or Java, we need to have something (pseudo code) like:
tmp = a;
a = b;
b = tmp;
Why Python can do it by a, b = b, a. What happened with it?
Not sure whether it is the right place for this question. But I do appreciate it if someone could give me some clues.
It's because python provides a special "tuple unpacking" syntax that many other languages don't have. I'll break apart what's going on:
The b, a on the right of the equals is making a tuple (remember, a tuple is pretty much the same as a list, except you can't modify it). The a, b on the left is a different syntax that's unpacking the tuple, i.e. it takes the first item in the tuple, and store it in the first variable listed, then it takes the second item and stored it in the second variable, and so forth.
This is what it looks like broken up in multiple steps:
a = 2
b = 3
my_tuple = a, b
print(my_tuple) # (2, 3)
b, a = my_tuple
print(a) # 3
print(b) # 2
And here's another, simpler examples of tuple unpacking, just to help wrap your mind around it:
x, y, z = (1, 2, 3)
print(x) # 1
print(y) # 2
print(z) # 3
By the way, Python's not the only one, Javascript can do it too, but with arrays:
[a, b] = [b, a];
I am a newbie in Python and I'm trying to learn Python through self-learning. I was trying to build Fibonacci series using a while loop. Here is my code, which doesn't return the desired result. Could anyone explain the problem?
a = 0
b = 1
while b<100:
print(b)
a = b
b = a + b
If we define a, b simultaneously like a, b = b, a+b, this works perfectly. Why is this happening? I don't understand because in both cases I am defining a and b the same way.
This is because programming languages like Python, and many others, execute the statements you write in the order you write them.
This means that by the time you execute b = a + b, the value of a has already changed in the previous line.
An easy way to solve this would be using a third variable to store the results temporarily.
a = 0
b = 1
c = 1
while c < 100:
print(c)
c = a + b
a = b
b = c
You are making one small mistake.
When you do a = b, you are changing the value of a. After this, when you do b=a+b, it is actually equivalent to b = b+b => b=2b.
To avoid this, use a temporary variable temp and storethe value of a in it. Then change the value of a using a = b. Then do, a = a+b.
Following is the code:
a=0
b=1
while b<100:
print(b)
temp = a
a = b
b = temp+b
When you do a, b = b, a+b, the previous value of a is used for calculating the new b, we have don a similar thing above by storing the previous value of a in temp
Operator "comma" (,) in Python is used to create a tuple, and it is allowed to omit the parentheses that surround a tuple. The expression a, b = b, a+b is actually an assignment of one tuple to another:
(a, b) = (b, a + b)
This statement is executed by evaluating the tuple constructor on the right-hand side (b, a + b). At this point, a new anonymous tuple (let's call it c) is created and the original values of a and b are not needed anymore. The tuple is then assigned elementwise to the tuple on the left-hand side. The new value of a becomes c[0] (that is, former b) and the new value of b becomes c[1] (that is, former a+b).
Your code is not working because you are changing the value of a before evaluating b. In the Fibonacci series, you want the previous value of a and b. You can use list as above or can introduce another variable to store values.
while True:
temp = a + b
if temp >100:
break
print(temp)
a = b
b = temp
For reference, here is a simple implementation using list:
lst = [0, 1]
while True:
temp = lst[-1]+lst[-2]
if temp>100:
break
lst.append(temp)
print(lst)
Title is a bit vague, here's my problem.
I'm trying to reduce the contents of one list based on the values to the right and left of the item in the other list.
An example:
If I have the following 2 lists.
a = [1,2,3,5,7,8]
b = [1,2,3,4,7]
and my constraint is a = b+1
I want to return
a = [2,3,5,8]
b = [1,2,4,7]
1 and 7 can't be in a because there is no 0 or 6 in b.
3 cant be in b because there is no 4 in a.
I'm having problems conceptualizing how I should even approach this.
My current attempt is:
c = []
d = []
for i in a:
for j in b:
if (i+1) == j or (i-1) ==j:
c.append(i)
d.append(j)
with the idea that I will then make a = c and b = d but the result i get is
c= [1,2,2,3,3,5,8]
d= [2,1,3,2,4,4,7]
I totally understand why I get those numbers in c and d but im afraid the logic of how to approach getting the right numbers totally escapes me. This is a small subset of a larger project I have to do but am getting caught up with this part in particular. Any help would be appreciated.
One simple and maybe inefficient answer (edited with list comprehension):
c = [el for el in a if (el-1) in b]
d = [el for el in b if (el+1) in a]
This question already has answers here:
Multiple assignment and evaluation order in Python
(11 answers)
Closed 7 years ago.
Help me understand difference between list assignment.
I have found that assignment like this
a[0] = b[0]
b[0] = a[0]
Is different from
a[0], b[0] = b[0], a[0]
The values of a and b in both the cases are different , however both of these assignment methods does the same , swapping.
You can run my sample code to see this
a = [0,1,2]
b = [3,4,5]
print "Value of a and b before swaping :"
print "value of a :" , a
print "value of b :" , b
print "\nswap in two line"
a[0] = b[0]
b[0] = a[0]
print "value of a :" , a
print "value of b :" , b
print "\nswap in one line"
# Reinitilizing value of a and b before performing swaping
a = [0,1,2]
b = [3,4,5]
a[0], b[0] = b[0], a[0]
print "value of a :" , a
print "value of b :" , b
How are two methods of assignment different? At the first glance they look the same and do the same thing.
however both of these assignment methods does the same [thing], swapping.
Not quite... The former example doesn't swap. Instead, it takes the first element of b and puts it in the first element of a. Then it takes the first element of a (which used to be the first element in b) and puts it back into b -- leaving a[0] and b[0] with the same value.
When it's all on the same line, python actually does something a little magical. It effectively creates a new tuple (b[0], a[0]) and then uses that tuple to assign things back into b and a. In other words, it behaves effectively the same as:
temp = (b[0], a[0])
a[0] = temp[0]
b[0] = temp[1]
notice how this is logically different from the first case you had.
The difference is the order in which assignment takes place. It has nothing to do with lists however.
The code
a = b
b = a
First assigns b to a, then assigns a to b resulting in both having the value that b had before.
On the other side
a, b = b, a
first evaluates b, a. And then take those values and assign to a and b. This results in a proper swap.