This question already has answers here:
Nested List Indices [duplicate]
(2 answers)
Having trouble making a list of lists of a designated size [duplicate]
(1 answer)
Closed 9 years ago.
I'm trying to figure out how to add a sub-list to a list in Python. For example, the code I was using before was just:
pop = [[],[],[],[],[],[],[],[],[],[]]
But I want to add user input to the length of the pop array, ie. how many arrays are added. I've looked at some other stackoverflow questions, and some of them suggested something like:
popLen = 5
pop = [None]*popLen
But when I try that it creates a list with 5 None elements instead of an empty array. I've tried:
pop = [[]]*popLen
What's the proper way to sub-lists?
pop = [[]]*popLen should work, but it is likely not what you want since it creates a list filled with the same nested list popLen times, meaning that a change to one of the list elements would appear in the others:
>>> a = [[]] * 3
>>> a[0].append(42)
>>> a
[[42], [42], [42]]
A better alternative would be
pop = [[] for _ in range(popLen)] # use xrange() in Python 2.x
which eliminates this issue:
>>> a = [[] for _ in range(3)]
>>> a[0].append(42)
>>> a
[[42], [], []]
You can do:
pop = [[] for x in range(popLen)]
Don't try to multiply [[]] - that will actually work, but will do something different than you expect (it will give you copies of the same list, so you cannot change them independently).
Related
This question already has answers here:
Understanding slicing
(38 answers)
Closed 2 years ago.
I have a simple question, looking at the following code:
letters = [hand[i]][:1] for i in range(5)]
What does the argument before 'for I in range(5)' do?? I can't seem to figure it out.
A simple list comprehension has three parts:
my_list = [A for B in C]
This translates exactly into:
my_list = []
for B in C:
my_list.append(A)
So the part before for determines what goes into the list you're creating.
In your case, you could also write it like this:
letters = []
for i in range(i):
letters.append(hand[i][:1]])
The upper piece of code is called list comprehension:
https://docs.python.org/3/tutorial/datastructures.html
So the upper code could be explicitly written out as:
hand # some data. From your code it should be a nested list, eq: hand = [ [...],[...],... ]
letters = []
for i in range(5): # iterates trough 0-4
element = hand[i][:1]
letters.append(element)
So this is just a very short way of constructing a list. You read it out lout like so:
For every i from range(5) take element(s) hand[i][:1] and assign it to a new list letters.
If your question is about the part hand[i][:1], then this is a slice from a nested list. For example:
hand = [
[0,1,2,3],
[4,5,6,7],
...
]
hand[0] == [0,1,2,3]
hand[0][:1] == [0]
hand[1][:1] == [4] # mind it is a slice, so you are left with a list!!
This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 2 years ago.
result_list = [[]]*3
print(result_list) #output [[],[],[]]
result_list[0].append(0)
result_list[1].append(33)
result_list[2].append(2)
print(result_list) #output [[0,33,2],[0,33,2],[0,33,2]]
# ???????????
list = [[],[],[]]
print (list) #output [[],[],[]]
list[0].append(0)
list[1].append(33)
list[2].append(2)
print (list) #output [[0],[33],[2]]
#normal
I want to make a list, where I can say, how many [] there should be (like in the first example with *3), but I want that list to behave like the second example, so that I can append to each [] individually.
[[]]*3
Actually is making one inner list [] which is referenced 3 times, so you are appending to the same list every time ... the alternative:
result_list = [[] for i in range(3)]
Why doesn't the first list do the same as the second?
Because the * operator on list simply adds new references to the original, so [[]]*3 is equivalent to (but faster than):
container = []
content = []
for _ in range(3):
container.append(content)
therefore you get the same inner list 3 times, rather than three different lists.
I want to make a list, where I can say, how many [] there should be (like in the first example with *3), but I want that list to behave like the second example, so that I can append to each [] individually.
l = [[] for _ in range(n)]
PS: don't call things list, list is a builtin, don't override builtins.
This question already has answers here:
What is the difference between Python's list methods append and extend?
(20 answers)
Closed 2 years ago.
I am trying to rotate the array by using following function:
def rotLeft(a,d):
temp=[]
temp.append(a[0:-1])
temp.insert(0,a[-1])
return temp
I should get output as 5 1 2 3 4
but I am getting 5,[1,2,3,4]
how to solve this problem
You must use Use .extend() instead of .append() as .append() and .insert() is for adding elements while .extend() is to merge two lists:
def rotLeft(a,d):
temp=[]
temp.extend(a[0:-1])
temp.insert(0,a[-1])
return temp
print(rotLeft([1,2,3,4,5], 1))
output:
[5, 1, 2, 3, 4]
You need to use temp.extend, not temp.append. The latter just adds one element to temp, the list [1,2,3,4] - this is why you end up with a nested list. extend on the other hand works as if each element from [1,2,3,4] is appended to temp.
This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 4 years ago.
I wonder why append add a number to every list that I have in my list. Not only to that one ([0]) that I have choosen. What's the difference between writing [0] or any other number next to append?
j = [[]] * 5
j[0].append(5) # add 5 to every list on list
j[1].append(4) # what's the diffrence? [1] or [0]; it adds number to every element anyway
print (j)
j.append(0) # add 0 to the main list
print (j)
This happens because your initial list j contains 5 references to the same object (so 5 copies to the same list). That's why everything you append goes to every list.
Instead, if you actually create 5 different sublists:
j = [[] for _ in range(5)]
Then it will work as you expect:
[[5], [4], [], [], [], 0]
There is no difference.
j = [[]] * 5
Repeats the same empty list instance five times, once at each index.
IOW, the initial empty list is referenced 5 times.
You could verify this:
id(j[0]) == id(j[1])
To instantiate a different empty list at each index requires a comprehension:
[[] for _ in range(5)]
This question already has answers here:
Understanding slicing
(38 answers)
Closed 9 years ago.
my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
I need to obtain a specific length of elements form a list starting at a specific index in Python. For instance I would like to get the three next elements from the [2] element above. Is there anyway to get the three elements from the specific index? I wont always know the next amount of elements I want to get, sometimes I may want to get two elements, sometimes eight elements, so x elements.
I know I can do my_list[2:] to get all of the elements from the third element to the end of the list. What I want to do is specify how many elements to read after the third element. Conceptually in my mind the example above would look like my_list[2:+3] however I know this wont work.
How can I achieve this or is it better to define my own function to give me this functionality?
You are actually very close:
>>> my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
>>> x = 3
>>> my_list[2:2+x]
[3, 4, 5]
>>>
As you can see, the answer to your question is to slice the list.
The syntax for slicing is list[start:stop:step]. start is where to begin, stop is where to end, and step is what to count by (I didn't use step in my answer).
my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
n = 3
print my_list[2:2+n]
Nothing smart here. But, you can pull n out and tweak it the way you want.
you should simply use
my_list[2:2+3]
and in general
list[ STARTING_INDEX : END_INDEX ]
which is equivalent to
list[ STARTING_INDEX : STARTING_INDEX + LENGTH ]
>>> my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
>>> my_list[2:3]
[3]
>>> my_list[2:2+3]
[3, 4, 5]