Inserting a sub list into a list n python - python

I have a list A=[[1,2],[2,3],[4,5]] and i want to insert [2,2] at index=1 in list A. What should i do? I am not suppose to use any package for this. The final array will be: A=[[1,2],[2,2],[2,3],[4,5]]
The following code I used but it is giving error:
A.insert([2,2],1)

you can use:
A.insert(1, [2, 2])
from the docs:
list.insert(i, x)
Insert an item at a given position. The first
argument is the index of the element before which to insert, so
a.insert(0, x) inserts at the front of the list, and a.insert(len(a),
x) is equivalent to a.append(x).

Related

Python: Accessing specific sublist element

Is there a way to be able to access specific sublist element?
For example:
list = [["a","b"],["c","d"]]
how to print out only b??
Thanks!
Firstly, it is a bad practice to name a variable as list as it is a keyword in Python. Say, it is changed to lis
lis = [["a","b"],["c","d"]]
To access b, you need to first get to the first element of lis, by lis[0]. This gives ["a", "b"]. Now you need to further go into it, so you do lis[0][1], This gives the 1-indexed element of lis[0], i.e., 'b'
You need to select the first sublist in your list (index 0), and then the second element of your sublist (index 1).
Result is list[0][1].

What does list.insert() in actually do in python?

I have code like this:
squares = []
for value in range(1, 5):
squares.insert(value+1,value**2)
print(squares)
print(squares[0])
print(len(squares))
And the output is :
[1, 4, 9, 16]
1
4
So even if I ask python to insert '1' at index '2', it inserts at the first available index. So how does 'insert' makes the decision?
From the Python3 doc:
list.insert(i, x)
Insert an item at a given position. The first
argument is the index of the element before which to insert, so
a.insert(0, x) inserts at the front of the list, and a.insert(len(a),
x) is equivalent to a.append(x).
What is not mentionned is that you can give an index that is out of range and Python will then append to the list.
If you dig into the Python implementation you find the following in the ins1 function that does the insertion:
if (where > n)
where = n;
So basically Python will max out your index to the length of the list.
Basically, it's similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end.

How can you loop over lists of tuples where you compare the tuple in one list to the other tuples in the same list?

for x in check:
this = sorted(x) #the first tuple
for y in check:
that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
if this == that:
check.remove(x)
print(check)
I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :
output of "check.remove(y)"
I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.
How the list 'check' looks like
How can I compare the tuples with each other in the same list and remove the second one that contains the same values?
Repeated removal from a list is never a good a idea since it is O(N).
You can do the cleaning in one non-nested run-through, however. It is better to build a clean list from scratch and possibly reassign it to the same variable:
seen, no_dupes = set(), []
for c in check:
s = tuple(sorted(c))
if s not in seen:
seen.add(s)
no_dupes.append(c)
# check[:] = no_dupes # if you must
Use in and not ==
for x in check:
this = sorted(x) #the first tuple
for y in check:
that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
if this in that:
check.remove(x)
# alternatively you might need to loop through this if its a tuple of tuples
# for t in this:
# if t in that:
# check.remove(x)
print(check)
Consider the instance [(1,1), (1,1), (1,1)]
In the first iteration, x is assigned to the first element in the list, y is also assigned to the first element, since x=y, remove x. Now when y is iterated to the second element, x=y, but now x has already been removed in the previous iteration. You should use dynamic programming:
new_check = []
for x in check:
this = sorted(x)
if x not in new_check:
new_check.append(x)
return new_check

Printing specific items out of a list

I'm wondering how to print specific items from a list e.g. given:
li = [1,2,3,4]
I want to print just the 3rd and 4th within a loop and I have been trying to use some kind of for-loop like the following:
for i in range (li(3,4)):
print (li[i])
However I'm Getting all kinds of error such as:
TypeError: list indices must be integers, not tuple.
TypeError: list object is not callable
I've been trying to change () for [] and been shuffling the words around to see if it would work but it hasn't so far.
Using slice notation you can get the sublist of items you want:
>>> li = [1,2,3,4]
>>> li[2:]
[3, 4]
Then just iterate over the sublist:
>>> for item in li[2:]:
... print item
...
3
4
You should do:
for i in [2, 3]:
print(li[i])
By range(n), you are getting [0, 1, 2, ..., n-1]
By range(m, n), you are getting [m, m+1, ..., n-1]
That is why you use range, getting a list of indices.
It is more recommended to use slicing like other fellows showed.
li(3,4) will try to call whatever li is with the arguments 3 and 4. As a list is not callable, this will fail. If you want to iterate over a certain list of indexes, you can just specify it like that:
for i in [2, 3]:
print(li[i])
Note that indexes start at zero, so if you want to get the 3 and 4 you will need to access list indexes 2 and 3.
You can also slice the list and iterate over the lists instead. By doing li[2:4] you get a list containing the third and fourth element (i.e. indexes i with 2 <= i < 4). And then you can use the for loop to iterate over those elements:
for x in li[2:4]:
print(x)
Note that iterating over a list will give you the elements directly but not the indexes.

python expression

I am new in python, and while reading a BeautifulSoup tutorial, I didn't understand this expression "[x for x in titles if x.findChildren()][:-1]" that i didn't understand? can you explain it
titles = [x for x in titles if x.findChildren()][:-1]
To start with [:-1], this extracts a list that contains all elements except the last element.
>>> a=[1,2,3,4,5]
>>> a[:-1]
[1, 2, 3, 4]
The comes the first portion, that supplies the list to [:-1] (slicing in python)
[x for x in titles if x.findChildren()]
This generates a list that contains all elements (x) in the list "titles", that satisfies the condition (returns True for x.findChildren())
It's a list comprehension.
It's pretty much equivalent to:
def f():
items = []
for x in titles:
if x.findChildren():
items.append(x)
return items[:-1]
titles = f()
One of my favorite features in Python :)
The expression f(X) for X in Y if EXP is a list comprehension It will give you either a generator (if it's inside ()) or a list (if it's inside []) containing the result of evaluating f(X) for each element of Y, by only if EXP is true for that X.
In your case it will return a list containing every element from titles if the element has some children.
The ending [:-1] means, everything from the list apart from the last element.
It's called a for comprehension expression. It is simply constructing a list of all titles in the x list which return true when the findChildren function is called upon them. The final statement substracts the last one from the list.

Categories