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.
Related
from my understanding shouldn't the print for X be the same on both? the answer i need is the one that comes from the list-comprehension, which is a new list where every element is -1 from the original list. But the for-loop one only gives 1 element, I also don't know how that element is calculated. Printing x just gives the last element of the list. I'm sure i'm doing something wrong but i'm not sure how to get a list from just using the for-loop. WHAT IS CONFUSING ME is that if the print(x) is part of the for loop it will print the elements of the desired list I need, but NOT in a list, which means the math I wrote works as intended, right?
list= [1,2,3,4,5]
#loop
x=[]
for i in list:
x=[i-1]
print(x)
#list comprehension
x=[i-1 for i in list]
print(x)
#confusing part where this print will be the same as the comprehension but not in a list form
x=[]
for i in list:
x=[i-1]
print(x)
First thing, list is a protected keyword. You should be using list_ at least (that's the naming convention if you really need to use list as the name).
The second iterates element by element, and prints each of the elements, what you want is in the loop to set each of the elements one by one, and then print x (not inside the loop).
list_= [1,2,3,4,5]
x=[]
for i in list_:
x.append(i-1)
print(x)
You should append like this:
lst= [1,2,3,4,5]
#loop
x=[]
for i in lst:
x.append(i-1)
print(x)
#output: [0, 1, 2, 3, 4]
#list comprehension
x=[i-1 for i in lst]
print(x)
#output: [0, 1, 2, 3, 4]
I have declared a list and sorted it.While iterating the second for loop I am getting :index out
of range error.
lst=[]
for i in range(5):
a=int(input())
lst.append(a)
lst.sort()
print(lst)
for i in range(0,len(lst)):
j=i+1
for j in range(len(lst)):
if lst[i]==lst[j]:
print("hii")
lst.pop(j)
print(lst)
As you remove elements from lst it's length change so your iteration breaks when it tries to access an empty index: "Index out of bound"
If you want to keep your structure you could catch that and exit the loop using a try/catch on IndexError but it's really ugly.
A more pythonic solution is to simply cast your list as a set then back to list. This works because sets remove all of their duplicate elements:
>>> list(set([1, 1, 2, 2, 3, 4,]))
[1, 2, 3, 4]
You shouldn't change the length of your list while iterating over it, I am assuming you want to delete all duplicates in your original list. You can use cast the list to a set with
set(lst)
before you sort or after you sort.
You're getting this error thrown as you are changing the length of a list whist iterating over it.
A simpler approach to removing all duplicates from a list would be to create a set based on the list which is then converted back to a list - this should be done before you sort your list as a set (by definition) does not preserve ordering of elements.
Using your example:
lst = []
for i in range(5):
a=int(input())
lst.append(a)
lst = list(set(lst)) # Remove duplicates from list
lst.sort() # Sort list
I have a list containing tuples. Each tuple holds 2 elements. I tried to print it with the following code, but it gives the error message:
TypeError: list indices must be integers or slices, not tuple
Relevant code:
for i in list:
for j in [1, 2]:
print(list[i][j])
With the idea of printing each element of the 1st tuple, each element of the 2nd tuple etc
Realise i in the loop is actually a tuple (an element of a list). So, you just need to print element of i like i[j]. list[i] makes no sense as i should be an integer, but it is actually an element of the list, that is a tuple. You must also be getting an error like this TypeError: list indices must be integers, not tuple. Well I am. So that should be a hint/explanation to you.
lst = [(1,2),(5,9)]
for i in lst:
for j in [0, 1]:
print(i[j])
print
Output:
1 2
5 9
You can unpack the tuple in the for loop
>>> tup_list = [(1,2), (3,4)]
>>> for a,b in tup_list:
... print(a,b)
...
1 2
3 4
You can use nested list comprehension:
[i for subset in list for i in subset] give you flat list
It's more pythonic!
This question already has answers here:
How can I iterate over overlapping (current, next) pairs of values from a list?
(12 answers)
Why do I get an IndexError (or TypeError, or just wrong results) from "ar[i]" inside "for i in ar"?
(4 answers)
Closed 7 months ago.
Given the following list
a = [0, 1, 2, 3]
I'd like to create a new list b, which consists of elements for which the current and next value of a are summed. It will contain 1 less element than a.
Like this:
b = [1, 3, 5]
(from 0+1, 1+2, and 2+3)
Here's what I've tried:
b = []
for i in a:
b.append(a[i + 1] + a[i])
The trouble is I keep getting this error:
IndexError: list index out of range
I'm pretty sure it occurs because by the time I get the the last element of a (3), I can't add it to anything because doing so goes outside of the value of it (there is no value after 3 to add). So I need to tell the code to stop at 2 while still referring to 3 for the calculation.
In your for loop, you're iterating through the elements of a list a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
Imagine if the list a would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a, which obviously is not there. This will give you an IndexError.
We can fix this issue by iterating over a range of indexes instead:
for i in range(len(a))
and access the a's items like that: a[i]. This won't give any errors.
In the loop's body, you're indexing not only a[i], but also a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError. Why? Because range(5) is essentially 0 1 2 3 4, so when the loop reaches 4, you will attempt to get the a[5] item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5] would mean getting the sixth element which does not exist.
To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.
There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
This does the job in only one line.
Reduce the range of the for loop to range(len(a) - 1):
a = [0, 1, 2, 3]
b = []
for i in range(len(a) - 1):
b.append(a[i] + a[i+1])
This can also be written as a list comprehension:
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
When you call for i in a:, you are getting the actual elements, not the indexes. When we reach the last element, that is 3, b.append(a[i+1]-a[i]) looks for a[4], doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like
for i in range(0, len(a)-1): Do something
Your current code won't work yet for the do something part though ;)
You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to zip the list with a slice of itself such that you can sum the pairs.
b = [i + j for i, j in zip(a, a[1:])]
i am trying to implement a string comparison algorithm in Python for one of my projects. As i am new to python, i'm learning on the go. But i'm stuck at a step of the algorithm.
At the moment i have list of lists. It is sorted and groupby the length.
mylist = list(list(i[1]) for i in itertools.groupby(sorted(mylist, key=len), len))
>>> [
[['pat'],['cut'],['rat']],
[['sat','pat'],['cut','pat']],
[['rat','cut','pat'],['put','cut','bat'],['mat','gut','lit']]
[[...]]...
]
If we consider mylist[2] elements in a column, it looks like this
mylist[2]
>>> [['rat','cut','pat'],
['put','cut','bat'],
['mat','gut','lit']]
i want to compare each column and return the most frequently occurring element count. i.e at index zero, it is 3(all three are different). For index one it is 2 (since 'cut' appears twice), and in index two, it is 3 again. likewise i need to repeat the process to all the lists of mylist.
It feels im stuck here. Can somebody suggest me a suitable method, perhaps a List Comprehension?
Thank You.
You can use set to extract the unique elements, and zip(*list_of_list) as a trick to "transpose" a list of list. Try this:
lst = [
[['pat'],['cut'],['rat']],
[['sat','pat'],['cut','pat']],
[['rat','cut','pat'],['put','cut','bat'],['mat','gut','lit']]
]
print map(lambda ll: [len(set(l)) for l in zip(*ll)], lst)
Output:
[[3], [2, 1], [3, 2, 3]]
Edit: To get the minimum value of each list, a trivial addition to the above will do:
print map(lambda ll: min([len(set(l)) for l in zip(*ll)]), lst)
Output:
[3, 1, 2]