I am trying to understand indexing in a list. I try:
x= [1,2,3,[4]]
x[0]=[34]
x[3][0]=95
which gives
[1, 2, 3, [95]]
but why is it not:
[34 2, 3, [95]]
?
Edit: apologies my code was:
x= [1,2,3,[4]]
y=list(x)
x[0]=[34]
x[3][0]=95
print (y)
Which gives the results I stated.
In this case, I believe python list mutability doing strange things.
When you call
y = list(x)
It copies each element in the list x over to the list y.
This means it avoids mutability in the first dimension, but because the third element is copied normally under the hood, and it is a list, it remains mutable.
You can find out a bit more in the docs (https://docs.python.org/3/library/stdtypes.html#list)
Also, as others have pointed out, you are setting
x[0] = [34]
Which sets the first element of x to a list, not a number so x would actually be
[ [34], 2, 3, [95] ]
Your example gives does not gives 1 at index 0.
You replace at index 0 the int 1 with a list containing one element of int 34 at index 0.
That will give you:
[[34], 2, 3, [95]]
Related
I am relatively new to python and I am still trying to learn the basics of the language. I stumbled upon a question which asks you to rearrange the list by modifying the original. What you are supposed to do is move all the even index values to the front (in reverse order) followed by the odd index values.
Example:
l = [0, 1, 2, 3, 4, 5, 6]
l = [6, 4, 2, 0, 1, 3, 5]
My initial approach was to just use the following:
l = l[::-2] + l[1::2]
However, apparently this is considered 'creating a new list' rather than looping through the original list to modify it.
As such, I was hoping to get some ideas or hints as to how I should approach this particular question. I know that I can use a for loop or a while loop to cycle through the elements / index, but I don't know how to do a swap or anything else for that matter.
You can do it by assigning to a list slice instead of a variable:
l[:] = l[::2][::-1] + l[1::2]
Your expression for the reversed even elements was also wrong. Use l[::2] to get all the even numbers, then reverse that with [::-1].
This is effectively equivalent to:
templ = l[::2][::-1] + l[1::2]
for i in range(len(l)):
l[i] = templ[i]
The for loop modifies the original list in place.
I am trying to solve a seemingly simple problem on Python. I am trying to update the last 3 element of a list to other integers. Here is the code:
list = [0,1,2,3,4]
for i in xrange(len(list[2:])):
list[2:][i] = 44444
print list
But when I print the list, it still remains the same. I observe the changes in debugger and I found that the list doesn't update in the loop. I tried searching elsewhere on Google and Stack Overflow, but none of them provide answers to this simple problem.
Let me know what you guys think about this. Thanks.
A slice of a list is a new list; it doesn’t reference the original or anything like that. Assign to list[2 + i] instead. (You can avoid making an extra slice to get the length in the same way.)
list = [0, 1, 2, 3, 4]
for i in xrange(len(list) - 2):
list[2 + i] = 44444
print list
A slice creates a new list, unless you assign to it:
>>> values = [0, 1, 2, 3, 4]
>>> values[-3:] = [4444] * 3
>>> values
[0, 1, 4444, 4444, 4444]
By using for i in xrange(len(list[2:])): you are reducing the length of list from 5 to 3. Your loop would iterate only for the first 3 list items.
Instead you could do something like this:
a=[0,1,2,3,4,5]
for i in range(3,len(a)):
a[i]=444
print(a)
Let's say I have an array
a = np.array[5, 3, 2]
and based on that array I want to return a new array in the form:
b = np.array[ [0, 1, 2, 3, 4], [0, 1, 2], [0, 1] ]
I've been trying:
for item in a:
b = np.hstack(np.arange(item))
print b
but this only gives me the elements without joining them into an array;
for item in a:
b = b.append((b[:], b[item]))
print b
but this approach blows up nicely with a:
AttributeError: 'numpy.ndarray' object has no attribute 'append'
I have tried other things, like:
b[item] = np.arange(item),
but that one complains about out-of-bounds indices.
And
b = np.zeros(len(a))
for item in np.arange(len(a)):
b[item] = np.arange(b[item])
print b
which complains with
ValueError: setting an array element with a sequence.
That last one is the one that looks more promising and, searching for some questions on this site (https://stackoverflow.com/a/13311979/531687) I know that the problem is that I am trying to fit a sequence where a value is expected, but I can't figure out my way around it.
How can I go about this?
This should work
b = [range(x) for x in a]
update
The brackets [...] here create a list and inside an iterator can be used to define the items in the list. In this case the items of of type range(x) for each item in a.
Note that there is a difference in implementation between python2 and python3 here. In python2 this actually generates a list of lists. In python3 however this generates a lists of generators (the python2 equivalent would be xrange), which is typically more efficient.
Beginner here, learning python, was wondering something.
This gives me the second element:
list = [1,2,3,4]
list.index(2)
2
But when i tried this:
list = [0] * 5
list[2] = [1,2,3,4]
list.index[4]
I get an error. Is there some way to pull the index of an element from an array, no matter what list it's placed into? I know it's possible with dictionaries:
info = {first:1,second:2,third:3}
for i in info.values:
print i
1
2
3
Is there something like that for lists?
The index method does not do what you expect. To get an item at an index, you must use the [] syntax:
>>> my_list = ['foo', 'bar', 'baz']
>>> my_list[1] # indices are zero-based
'bar'
index is used to get an index from an item:
>>> my_list.index('baz')
2
If you're asking whether there's any way to get index to recurse into sub-lists, the answer is no, because it would have to return something that you could then pass into [], and [] never goes into sub-lists.
list is an inbuilt function don't use it as variable name it is against the protocol instead use lst.
To access a element from a list use [ ] with index number of that element
lst = [1,2,3,4]
lst[0]
1
one more example of same
lst = [1,2,3,4]
lst[3]
4
Use (:) semicolon to access elements in series first index number before semicolon is Included & Excluded after semicolon
lst[0:3]
[1, 2, 3]
If index number before semicolon is not specified then all the numbers is included till the start of the list with respect to index number after semicolon
lst[:2]
[1, 2]
If index number after semicolon is not specified then all the numbers is included till the end of the list with respect to index number before semicolon
lst[1:]
[2, 3, 4]
If we give one more semicolon the specifield number will be treated as steps
lst[0:4:2]
[1, 3]
This is used to find the specific index number of a element
lst.index(3)
2
This is one of my favourite the pop function it pulls out the element on the bases of index provided more over it also remove that element from the main list
lst.pop(1)
2
Now see the main list the element is removed..:)
lst
[1, 3, 4]
For extracting even numbers from a given list use this, here i am taking new example for better understanding
lst = [1,1,2,3,4,44,45,56]
import numpy as np
lst = np.array(lst)
lst = lst[lst%2==0]
list(lst)
[2, 4, 44, 56]
For extracting odd numbers from a given list use this (Note where i have assingn 1 rather than 0)
lst = [1,1,2,3,4,44,45,56]
import numpy as np
lst = np.array(lst)
lst = lst[lst%2==1]
list(lst)
[1, 1, 3, 45]
Happy Learning...:)
In your second example, your list is going to look like this:
[0, 0, [1, 2, 3, 4], 0, 0]
There's therefore no element 4 in the list.
This is because when you set list[2], you are changing the third element, not updating further elements in the list.
If you want to replace a range of values in the list, use slicing notation, for example list[2:] (for 'every element from the third to the last').
More generally, the .index method operates on identities. So the following will work, because you're asking python where the particular list object you inserted goes in the list:
lst = [0]*5
lst2 = [1,2,3,4]
lst[2] = lst2
lst.index(lst2) # 2
The answer to your question is no, but you have some other issues with your code.
First, do not use list as a variable name, because its also the name of the built-in function list.
Secondly, list.index[4] is different than list.index(4); both will give errors in your case, but they are two different operations.
If you want to pull the index of a particular element then index function will help. However, enumerate will do similar to the dictionary example,
>>> l=['first','second','third']
>>> for index,element in enumerate(l):
... print index,element
...
output
0 first
1 second
2 third
I was instructed to prevent this from happening in a Python program but frankly I have no idea how this is even possible. Can someone give an example of how you can slice a list and insert something into it to make it bigger? Thanks
>>> a = [1,2,3]
>>> a[:0] = [4]
>>> a
[4, 1, 2, 3]
a[:0] is the "slice of list a beginning before any elements and ending before index 0", which is initially an empty slice (since there are no elements in the original list before index 0). If you set it to be a non-empty list, that will expand the original list with those elements. You could also do the same anywhere else in the list by specifying a zero-width slice (or a non-zero width slice, if you want to also replace existing elements):
>>> a[1:1] = [6,7]
>>> a
[4, 6, 7, 1, 2, 3]
To prevent this from happening you can subclass the builtin list and then over-ride these methods for details refer here