473,770 Members | 1,902 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Newbie needs help on using for and lists

4 New Member
I'm really really newbie, almost no knowledge about python.

The problem I have is :
example)
Expand|Select|Wrap|Line Numbers
  1.  a = [ 1, 2, 3, 4, 5, 6, 7 ]
  2.  for n in a:
  3.      if a[n] < 4:
  4.         del a[n]
if I code like this, an error occurs, because the number of elements is changed.
so, what should I do to do this withour any error.
Is there any way to access list datas simultaneously?
Aug 21 '07 #1
6 1063
Strider1066
11 New Member
Rather than deleting items that fail the test, try copying the good'uns to a new list.
Aug 21 '07 #2
ilikepython
844 Recognized Expert Contributor
I'm really really newbie, almost no knowledge about python.

The problem I have is :
example)
Expand|Select|Wrap|Line Numbers
  1.  a = [ 1, 2, 3, 4, 5, 6, 7 ]
  2.  for n in a:
  3.      if a[n] < 4:
  4.         del a[n]
if I code like this, an error occurs, because the number of elements is changed.
so, what should I do to do this withour any error.
Is there any way to access list datas simultaneously?
I don't get what you are trying to do. You have a list of indexes (??) that you use to acces that same list? Is this what you want:
Expand|Select|Wrap|Line Numbers
  1. a = range(1, 8) # generates a list like yours
  2. new = []
  3. for n in a:
  4.     if n < 4:
  5.         new.append(n)
  6.  
Or you could use filter():
Expand|Select|Wrap|Line Numbers
  1. a = range(1, 8)
  2. new = filter(lambda x: x < 4, a)
  3.  
Or maybe a list comprehension is clearer:
Expand|Select|Wrap|Line Numbers
  1. a = range(1, 8)
  2. new = [n for n in a if n < 4]
  3.  
Aug 21 '07 #3
bartonc
6,596 Recognized Expert Expert
I'm really really newbie, almost no knowledge about python.

The problem I have is :
example)
Expand|Select|Wrap|Line Numbers
  1.  a = [ 1, 2, 3, 4, 5, 6, 7 ]
  2.  for n in a:
  3.      if a[n] < 4:
  4.         del a[n]
if I code like this, an error occurs, because the number of elements is changed.
so, what should I do to do this withour any error.
Is there any way to access list datas simultaneously?
Our new friend, Strider1066, has a good suggestion.
For a quick copy of a simple list, use a "slice":
Expand|Select|Wrap|Line Numbers
  1. >>> for i, item in enumerate(a[:]):  # A "slice" from beginning to end
  2. ...     if item < 4:
  3. ...         del a[i]
  4. ...         
  5. >>> a
  6. [2, 4, 6, 7]
  7. >>> 
Aug 21 '07 #4
ilikepython
844 Recognized Expert Contributor
Our new friend, Strider1066, has a good suggestion.
For a quick copy of a simple list, use a "slice":
Expand|Select|Wrap|Line Numbers
  1. >>> for i, item in enumerate(a[:]):  # A "slice" from beginning to end
  2. ...     if item < 4:
  3. ...         del a[i]
  4. ...         
  5. >>> a
  6. [2, 4, 6, 7]
  7. >>> 
Are you sure that works? I mean, 2 is not greater than 4. It works with a.remove() but I get the same results like yours when I use del. I never actually use del. What does it do?
Aug 21 '07 #5
bartonc
6,596 Recognized Expert Expert
Are you sure that works? I mean, 2 is not greater than 4. It works with a.remove() but I get the same results like yours when I use del. I never actually use del. What does it do?
OOoooops! Can't rely on the index into a changing list.
Remove works because it doesn't rely on the index of the item.
Expand|Select|Wrap|Line Numbers
  1. >>> a = [ 1, 2, 3, 4, 5, 6, 7 ]
  2. >>> for item in a[:]:  # A "slice" from beginning to end
  3. ...     if item < 4:
  4. ...         a.remove(item)
  5. ...         
  6. >>> a
  7. [4, 5, 6, 7]
  8. >>> a = [ 1, 2, 3, 4, 5, 6, 7 ]
  9. >>> for item in a[:]:  # A "slice" from beginning to end
  10. ...     if item < 4 or item == 7:
  11. ...         a.remove(item)
  12. ...         
  13. >>> a
  14. [4, 5, 6]
  15. >>> 
Nice catch, my friend. Thank you.
Aug 21 '07 #6
diediealldie
4 New Member
Thank you everyone, it was wiser to copy and replace lists.

I'm going to like here. :) thx
Aug 21 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

31
2997
by: Raymond Hettinger | last post by:
Based on your extensive feedback, PEP 322 has been completely revised. The response was strongly positive, but almost everyone preferred having a function instead of multiple object methods. The updated proposal is at: www.python.org/peps/pep-0322.html In a nutshell, it proposes a builtin function that greatly simplifies reverse iteration. The core concept is that clarity comes from specifying a sequence in a forward direction and...
4
1831
by: wageslave | last post by:
Hi folks, I have a question about using consequtive combo boxes on a form. I am designing a basic library database for a small community organisation which deals with inner city problems and issues. They don't have a librarian on staff so I am trying to make things as easy as possible for them. To help them catalogue new items I have developed a set of 'categories' and 'classes' for all new stock. 'Categories' are the wide subject...
8
1723
by: karokat | last post by:
Hi, I want to learn how to program and python seems to be the most intuitive language according to various internet sources - but I'm not sure if it's best for newbies... please advise.. Anyway, my first project I would like to make is a simple proggie - a simple note 'library', with basic formattable text, to store, edit and access my notes. Express Notes is the prog I currently use but there's things in it I want to customise to my personal...
3
1484
by: donchoi | last post by:
Hi, newbie here, sorry. I have a couple of basic Python questions. 1) How do I open 'datafile' and skip to the ith line for reading? I have a loop counter i for this purpose. The data file is very long, and I'd like to read just 100 lines in at a time or so. 2) Is there any easy way to determine the length of a text file (in lines) besides opening the file, reading each line and using a counter?
259
7120
by: user923005 | last post by:
It would be really nice if C could adopt a really nice algorithms library like C++'s STL + BOOST. The recent "reverse the words in this sentence" problem posted made me think about it. It's like 5 lines to do it in C++ because of all the nifty algorithms that come with the language (I think BOOST is going to get bolted on to the C++ language like STL did). It's a lot more work in C than C++. Why doesn't C have stacks,
2
2316
by: Man4ish | last post by:
I have created Graph object without vertex and edge property.It is working fine. #include <boost/config.hpp> #include <iostream> #include <vector> #include <string> #include <boost/graph/adjacency_list.hpp> #include <boost/tuple/tuple.hpp> #include <set> using namespace std;
2
2445
by: clouddragon | last post by:
Hi, i am in desperate need for any help regarding one of my assignments. I am to write a python program that lists the numbers that are composite from 1 to n(input) and write it to an external txt. I was able to write something that checks whether something is composite or not but able to incorporate it into a loop as such. for example: n = 50 then the composite numbers are 4 6
7
1515
by: idiolect | last post by:
Hi all - Sorry to plague you with another newbie question from a lurker. Hopefully, this will be simple. I have a list full of RGB pixel values read from an image. I want to test each RGB band value per pixel, and set it to something else if it meets or falls below a certain threshold - i.e., a Red value of 0 would be changed to 50. I've built my list by using a Python Image Library statement akin to the following:
8
1608
by: jch | last post by:
Sorry for the newbie question but I'm trying to learn Visual Studio. I've got VS Express 2008 and I'm using visual basic. I'm trying to learn how to deploy a program so I've written a very basic windows application (lets call it TWinApp1) with just a couple of buttons and a text box. It is very simple and runs fine in the debugger. Using TWinApp1 I'm trying to learn how to create a setup program to install an application on a system....
0
9453
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10254
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10099
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10036
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8929
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.