How to Create a List in Python
Edited by Zeal, Teresa, Writelf, Maluniu and 9 others
In Python, there is no such thing as an array. Instead, we have lists, which are even more flexible. In arrays, you can only have one data type. (String, integer, float, etc.) In lists, you can combine all kinds of data types in one, and you won't get any errors.
EditSteps
-
1Open an interactive window. Try using IDLE instead of the Python command prompt.
- To open IDLE, go to Start Menu > All Programs > Python (version number) > IDLE (Python GUI).
Ad -
2Next, create your list.
- First, write your variable name. This can be pretty much anything, but can not begin with a number. We will use foo for the name.
- Now, type an equal sign to assign this name to something.
- Third, the hard part. Type a left bracket, ([), then some kind of datatype. For example, a string is enclosed in quotes: 'This is a string'. An integer needs no quotes: 56. For this list, we will use 1,2,3. So: [1,2,3]. What you have now should look like: foo = [1,2,3].
-
3You could also use a string, like foo = ['John', 'John2', 'John3']. All list items are separated by commas.Ad
EditVideo
EditTips
- You can use list comprehension to make harder jobs easier.
- You can create new lists by assigning existing ones to an empty variable. Like:
foo2 = foo
EditWarnings
- Make sure you put commas in between items.
Article Info
Thanks to all authors for creating a page that has been read 10,283 times.