1 / 4

Lists in Python

Lists in Python. Creating lists. Simple ways to create a list. Hard code the values mylist = [3, 9, ‘a’, 7.2] Using the replication operator mylist = [0] * 100 (gives a list with 100 zeros ) Use the split method on a string Use the readlines method on a file

betsy
Download Presentation

Lists in Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lists in Python Creating lists

  2. Simple ways to create a list • Hard code the values mylist = [3, 9, ‘a’, 7.2] • Using the replication operator • mylist = [0] * 100 (gives a list with 100 zeros) • Use the split method on a string • Use the readlines method on a file • Put [] around a variable if my_num is 5, then [ my_num] is the list [5]

  3. Append vs. Concatenate • Both can be used to add to an existing list but their syntax is not the same • The concatenate operator + uses two lists and creates a bigger one • You cannot say mylist = mylist + “joe”, it must be mylist = mylist + [“joe”] • Append is a method which adds an element to the right end of a list – any type of data • mylist.append(“3”) makes mylist one element longer

  4. List accumulation • Either concatenation or append can be used with lists as accumulators • Initialize the list variable as an empty list [] • inside your loop either concatenate or append the new item onto your list variable

More Related