Python List of element output is discontinuous [duplicate] - python

This question already has answers here:
What is the id( ) function used for?
(13 answers)
Closed 2 years ago.
I knew when python's list append element,the element is appended to tail. I tried to output the element of the list, why the element's address is out of order? Please help me out,thanks!
list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in list:
print('i:{}, id:{}'.format(i,id(i)))
the output is:
--append--
i:2, id:140711739437936
i:10, id:140711739438192
i:3, id:140711739437968

The id() function returns a unique id for the specified object.
You need to use the index of the list
list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in list:
print('i:{}, id:{}'.format(i,list.index(i))) # replace id with list.index

id() returns identity (unique integer) of an object...
a=3
print(id(3)) #9752224
You can use this
list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in enumerate(list): #enumerate return an enumerate object.if list it [(0,2),(1,10),(2,3)]
print('i:{}, id:{}'.format(i[1],i[0]))# for getting index number i[0]

The id function is rarely used in actual programming, and usually, you use the list index to deal with lists. Your example will look something like:
mylist = []
mylist.append(2)
mylist.append(10)
mylist.append(3)
print(mylist)
Output:
[2,10, 3]
Sample code:
for x in range(len(mylist)):
print(x, mylist[x])
Output:
0, 2
1, 10
2, 3
You may check one of the good python tutorials on the web such as the one on the python web page: https://docs.python.org/3/tutorial/

Related

what comes before "for i in range (...)" [duplicate]

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!!

Rotateleft array [duplicate]

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.

Converting list of one string to list of integers [duplicate]

This question already has answers here:
How to convert a string list into an integer in python [duplicate]
(6 answers)
Closed 7 years ago.
I have a list that looks like this:
mylist = ['1,2,3']
It is a list of one string. I want to convert this to a list of integers like:
mylist = [1,2,3]
I tried [int(x) for x in mylist.split(',')] but it doesn't work.
Can someone please help? Thanks in advance.
Using list comprehension. split is a string method
[int(j) for i in mylist for j in i.split(',')]
The reason your code doesn't work is that your list only contains one item - "1,2,3". Split the first (and only) item in the list on comma, then map int to the items you get:
mylist = ['1,2,3']
print map(int, mylist[0].split(","))
Prints
[1, 2, 3]
If you have more than one item in your list, you can do
print map(int, [sub for item in mylist for sub in item.split(",")])

Python lists get specific length of elements from index [duplicate]

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]

how to convert two lists into a dictionary (one list is the keys and the other is the values)? [duplicate]

This question already has answers here:
How can I make a dictionary (dict) from separate lists of keys and values?
(21 answers)
Closed 6 years ago.
This is code in IDLE2 in python, and error.
I need to include each "data" element as key and value "otro", in an orderly manner. Well "data" and "otro" it's list with 38 string's, as for "dik" it's an dictionary.
>>> for i in range(len(otro)+1):
dik[dato[i]] = otro[i]
Traceback (most recent call last):
File "<pyshell#206>", line 2, in <module>
dik[dato[i]] = otro[i]
IndexError: list index out of range
>>>
this problem is range(0, 38)
output -> (0, 1,2,3 ... 37) and it is all messy
I think something like:
dik = dict(zip(dato,otro))
is a little cleaner...
If dik already exists and you're just updating it:
dik.update(zip(dato,otro))
If you don't know about zip, you should invest a little time learning it. It's super useful.
a = [ 1 , 2 , 3 , 4 ]
b = ['a','b','c','d']
zip(a,b) #=> [(1,'a'),(2,'b'),(3,'c'),(4,'d')] #(This is actually a zip-object on python 3.x)
zip can also take more arguments (zip(a,b,c)) for example will give you a list of 3-tuples, but that's not terribly important for the discussion here.
This happens to be exactly one of the things that the dict "constructor" (type) likes to initialize a set of key-value pairs. The first element in each tuple is the key and the second element is the value.
The error comes from this: range(len(otro)+1). When you use range, the upper value isn't actually iterated, so when you say range(5) for instance, your iteration goes 0, 1, 2, 3, 4, where position 5 is the element 4. If we then took that list elements and said for i in range(len(nums)+1): print nums[i], the final i would be len(nums) + 1 = 6, which as you can see would cause an error.
The more 'Pythonic' way to iterate over something is to not use the len of the list - you iterate over the list itself, pulling out the index if necessary by using enumerate:
In [1]: my_list = ['one', 'two', 'three']
In [2]: for index, item in enumerate(my_list):
...: print index, item
...:
...:
0 one
1 two
2 three
Applying this to your case, you can then say:
>>> for index, item in enumerate(otro):
... dik[dato[index]] = item
However keeping with the Pythonicity theme, #mgilson's zip is the better version of this construct.

Categories