Slicing a List of Strings - python

Am I able to slice a list of strings? If it is possible could anyone please tell me how to do it so that I am able to print out a particular string instead of the five that make up the list.
Cheers.
eg.
mylist = ['apples' 'oranges' 'lemons' 'cucumbers' 'bananas']
print 'orange'
** The programming language i am using is python. Every time I code it mylist[2] it comes out as an error. The list I am using is extracting the strings from a html rss feed. Each string is a new news heading. However, even when it updates constantly there are always 5 strings in the list and it tells me list index out of range. But if I just print the entire list it works fine**
#URLS for RSS Feeds
url_national = 'http://feeds.news.com.au/public/rss/2.0/news_national_3354.xml'
url_sport = 'http://feeds.news.com.au/public/rss/2.0/news_sport_3168.xml'
url_world = 'http://feeds.news.com.au/public/rss/2.0/news_theworld_3356.xml'
url_technology = 'http://feeds.news.com.au/public/rss/2.0/news_tech_506.xml'
def headlines (url):
web_page = urlopen(url)
html_code = web_page.read()
web_page.close()
return findall(r'<item><title>([^<]*)</title>', html_code)
#headlines list
list_national = [headlines(url_national)]
list_sport = [headlines(url_sport)]
list_world = [headlines(url_world)]
list_technology = [headlines(url_technology)]
def change_category():
if label_colour.get() == 'n':
changeable_label['text'] = list_national #here I would slice it but it doesn't work
elif label_colour.get() == 's':
changeable_label['text'] = list_sport
elif label_colour.get() =='w':
changeable_label['text'] = list_world
else:
changeable_label['text'] = list_technology
the reason I need to slice it into individual heading is so when the radio button is pressed for my GUI it prints them in a numbered list on the label not all just running on one line next to them - sorry i hope that makes sense

What language are you using here? Usually you can use an index to access a particular entry in a list. For example:
print myList[1]

Commas are missing in your list creation. You have to do it like this:
mylist = ['apples', 'oranges', 'lemons', 'cucumbers', 'bananas']
And you will be able to work with your list
mylist[0] # 'apples'
mylist[-1] # 'bananas'
mylist[2] # 'lemons'

I think the error you are getting is something like this:
mylist = ['apples' 'oranges' 'lemons' 'cucumbers' 'bananas']
print mylist[5]
IndexError: list index out of range
The reason is the elements in a list are indexed from 0 not 1.
The mylist has 5 elements starting from 0 to 4. So when you call print mylist[5] it will definitely give an error as there is no 6th element in the list.
Here is the official doc regarding list please have a look.
I hope it was helpful!

Related

How do I print specific items from a python list?

I am trying to print multiple items from a list in Python. I have looked at many examples but I am unable to get them to work. What is a good way to print items from the imported list based on their list index.
The commented out example in my code is what I thought will work and cant find a simple solution.
items = []
with open('input.txt') as input_file:
for line in input_file:
items.append(line)
print(items[5],items[6])
#print(items[5,6,7]
One way to do it would be with a for loop.
item_list = ['a','b','c','d','e','f','g','i'] # an example list.
index_to_print = [5,6,7] # add all index you want to print to this list.
for i in item_list:
if item_list.index(i) in index_to_print:
print(i)
update: instead of looping through the whole item_list, we can loop through the indexes you want to print.
for i in index_to_print:
if i < len(item_list):
print(item_list[i])
else:
print('given index is out of range.')

How to determine row index using a single print statement?

Given the data for the row index to be found as max_sw and list is sw_col.
I tried this and some other variation, but nothing worked.
print(i for i in range(len(sw_col)) if sw_col[i]== max_sw)
The line you have is almost there. If you put the generator into a list and use only index position zero, this will give you the correct answer:
sw_col = ['a','b','c']
max_sw = 'c'
print([i for i in range(len(sw_col)) if sw_col[i]== max_sw][0]) # prints 2
A more concise solution would be to look up the item directly in the list, like so:
sw_col = ['a','b','c']
max_sw = 'c'
print(sw_col.index(max_sw)) # prints 2

inserting into a list but ensuring that there isnt multiple insertions in the list

Ive been trying to create a part of code that takes data from an excel file then adds it into a list but only once. all other times should be ignored, ive managed to get all the data i need, just need to know how to pop unwanted duplicates. Also wondering if i should do this in a dictionary and how it would be done if i did
for cellObj in rows:<br>
Lat = str(cellObj[5].value)<br>
if 'S' in Lat:<br>
majorCity.append(str(cellObj[3].value))<br>
print(majorCity)<br>
elif majorCity == majorCity:<br>
majorCity.pop(str(cellObj[3].value))<br>
You can use set(), it will remove duplicates from a sequence.
a= set()
a.add("1")
a.add("1")
print a
Output:
set(['1'])
set is indeed a good way to do this:
>>> my_list = [1,1,2,2]
>>> my_list_no_dups = list(set(my_list))
>>> my_list_no_dups
[1, 2]
but it will not necessarily preserve the order of the list. If you do care about the order, you can do it like this:
my_list_no_dups = []
for item in my_list:
if item not in my_list_no_dups:
my_list_no_dups.append(item)

List Indexing and Reverse Indexing

Python and Indexing
I've been working on a vanilla Python code to separate data from a csv. My goal is to recreate this code using multiple strategies in order to better my understanding of Python. Improvements to this code will come later. The code I have works, but there are a couple things that I don't understand. Here it is:
with open('C:\My Super Secret Path\primary_debates_cleaned.csv') as primaryData:
headers = primaryData.readline().strip('\n').split(',')
flag = 0
for lines in primaryData:
sepInit = lines.strip('\n').split('"')
if flag == 1:
sep1 = [item for item in sepInit[0].split(',') if item is not '']
sep2 = sepInit[1]
sep3 = [item for item in sepInit[2].split(',') if item is not '']
#sep4 = sepInit[3]
sep4 = sepInit[-2]
#sep5 = sepInit[4].strip(',')
sep5 = sepInit[-1].strip(',')
#sepFinal = [sep1[0], sep1[1], sep2, sep3[0], sep3[1], sep4, sep5]
sepFinal = [sep1[0], sep1[1], sep2, sep3[0:1], sep3[1:2], sep4, sep5]
if flag == 0:
sepFinal = headers
flag = 1
print sepFinal
My first question concerns this snippet, specifically indexing:
#sep4 = sepInit[3]
sep4 = sepInit[-2]
#sep5 = sepInit[4].strip(',')
sep5 = sepInit[-1].strip(',')
The commented part is what I want to do, and the uncommented part is what works. It seems like I have to reverse the index in order to grab the proper information. The "type" seems to be the same, both being lists. Is there something I'm doing incorrectly at the start, or am I missing something simple here?
My next question has a similar flavor, from the snippet below:
#sepFinal = [sep1[0], sep1[1], sep2, sep3[0], sep3[1], sep4, sep5]
sepFinal = [sep1[0], sep1[1], sep2, sep3[0:1], sep3[1:2], sep4, sep5]
Why is it that I can get the information I need from sep1 simply using 0 and 1, but I cannot do the same for sep3?
Finally, when printing out the list sepFinal, the elements for sep4 and sep5 appear as lists. Everything else is just an element of the list sepFinal, but sep4 and sep5 are lists within the list. If this needs clarification, let me know. So, why do sep4 and sep5 appear as lists within my list?
EDIT0: There are no inputs to this. I am going into the PowerShell, and typing python mySecretProgramName.py to run it. The print sepFinal shows the following, parenthesized:
>>> [element 1, element 2, element 3, [element 4], [element 5]]
From the start, I'd like it to be:
>>> [element 1, element 2, element 3, element 4, element 5]
EDIT1: The negative indexing was needed due to data being improperly split. The length of sepInit was changing, so the indexing was not correct. Thank you to #martineau for pointing out this possibility. I tested this by simply putting print(len(sepInit)) after sepInit in the loop.
Negative indexing information: someList[-1] grabs the last item in a list, someList[-2] grabs the second to last item in a list, etc.
EDIT2: This concerns sep3[0:1] and the like. This essentially takes slice of the list, where sep3[0:1] would return whatever element falls between the places 0 and 1.

Python, Lists - Use 'Item' as integer variable

Sorry for the poor title, basically I want to access a list item based on another list item:
catList = [john, james, jack]
dateList = [1y, 2y, 3m]
for item in catList:
if item in typeList[1]:
calendar += 1
if item in typeList[2]:
connector += 1
print dateList[item]
It's the last line that I want to achieve, essentially to print the value of dateList which corresponds to the value of catList.
Any ideas? Thanks
Edit: My catDict & dateDict are lists so they don't have keys, just values.
If the keys to catDict are numeric strings you can use print dateDict[int(item)]. Otherwise, I'm uncertain - we need to see what the declaration of catDict looks like.
If you're using lists you want to do this:
for idx, val in enumerate(catList):
print dateList[idx]

Categories